DRF框架自定义异常信息处理
(exc, context)
| 23 | |
| 24 | |
| 25 | def format_exception_handler(exc, context): |
| 26 | """DRF框架自定义异常信息处理 |
| 27 | """ |
| 28 | # Call REST framework"s default exception handler first, |
| 29 | # to get the standard error response. |
| 30 | response = exception_handler(exc, context) |
| 31 | request = context.get("request") |
| 32 | if not request: |
| 33 | return response |
| 34 | api_type = request.META.get("HTTP_API_TYPE") |
| 35 | if api_type != "coding": |
| 36 | return response |
| 37 | |
| 38 | if response is not None: |
| 39 | logger.warning("exception response: %s" % response.data) |
| 40 | custom_response_data = {"status_code": response.status_code, "code": -1} |
| 41 | # 异常数据为字符串,则直接使用 |
| 42 | if isinstance(response.data, str): |
| 43 | custom_response_data["cd_error"] = response.data |
| 44 | # 异常数据为list,将其连接成为字符串 |
| 45 | elif isinstance(response.data, list): |
| 46 | custom_response_data["cd_error"] = ";".join(response.data) |
| 47 | # 异常数据为dict,且包含 detail字段,则将其detail替换为 cd_error |
| 48 | elif isinstance(response.data, dict) and response.data.get("detail"): |
| 49 | custom_response_data["cd_error"] = response.data.pop("detail") |
| 50 | custom_response_data.update(**response.data) |
| 51 | # 异常类型为 ValidationError 时,补充err_msg,并按固定格式存放数据 |
| 52 | elif isinstance(exc, ValidationError): |
| 53 | invalid_fields = [] |
| 54 | for field, value in response.data.items(): |
| 55 | invalid_fields.append({"field": field, "message": value}) |
| 56 | custom_response_data["invalid_fields"] = invalid_fields |
| 57 | custom_response_data["cd_error"] = "数据格式不准确" |
| 58 | else: |
| 59 | custom_response_data = response.data |
| 60 | response.data = custom_response_data |
| 61 | response.status_code = HTTP_200_OK |
| 62 | logger.info("coding error response data: %s" % custom_response_data) |
| 63 | return response |
| 64 | |
| 65 | |
| 66 | def custom_exception_handler(exc, context): |