MCPcopy Create free account
hub / github.com/Tencent/CodeAnalysis / format_exception_handler

Function format_exception_handler

server/projects/main/util/handlers.py:25–66  ·  view source on GitHub ↗

DRF框架自定义异常信息处理

(exc, context)

Source from the content-addressed store, hash-verified

23
24
25def 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 if isinstance(exc, BaseServerError):
37 return Response({'code': exc.code, 'msg': exc.msg}, status=exc.status_code)
38 else:
39 return response
40
41 if response is not None:
42 logger.warning("exception response: %s" % response.data)
43 custom_response_data = {"status_code": response.status_code, "code": -1}
44 # 异常数据为字符串,则直接使用
45 if isinstance(response.data, str):
46 custom_response_data["cd_error"] = response.data
47 # 异常数据为list,将其连接成为字符串
48 elif isinstance(response.data, list):
49 custom_response_data["cd_error"] = ";".join(response.data)
50 # 异常数据为dict,且包含 detail字段,则将其detail替换为 cd_error
51 elif isinstance(response.data, dict) and response.data.get("detail"):
52 custom_response_data["cd_error"] = response.data.pop("detail")
53 custom_response_data.update(**response.data)
54 # 异常类型为 ValidationError 时,补充err_msg,并按固定格式存放数据
55 elif isinstance(exc, ValidationError):
56 invalid_fields = []
57 for field, value in response.data.items():
58 invalid_fields.append({"field": field, "message": value})
59 custom_response_data["invalid_fields"] = invalid_fields
60 custom_response_data["cd_error"] = "数据格式不准确"
61 else:
62 custom_response_data = response.data
63 response.data = custom_response_data
64 response.status_code = HTTP_200_OK
65 logger.info("coding error response data: %s" % custom_response_data)
66 return response
67
68
69def custom_exception_handler(exc, context):

Callers

nothing calls this directly

Calls 4

warningMethod · 0.80
getMethod · 0.45
updateMethod · 0.45
infoMethod · 0.45

Tested by

no test coverage detected