# 简介
当程序中出现异常时,我们想要返回的是包含异常信息的json数据。返回正常的信息和异常信息的格式一致化。
# 操作
- 自定义json返回的格式
libs/response.py
代码语言:javascript复制from rest_framework.response import Response
class JsonResponse(Response):
def __init__(self, data=None, code=None, msg=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None):
rsp_data = {"code": code, "message": msg, "data": data}
super(JsonResponse, self).__init__(data=rsp_data, status=status, template_name=template_name,
headers=headers,
exception=exception, content_type=content_type)
- 自定义全局的异常处理方法 libs/exceptions.py
from rest_framework import status
from rest_framework.views import exception_handler
from libs.response import JsonResponse
class DataException(Exception):
def __init__(self, message="", code=0, status=status.HTTP_400_BAD_REQUEST, data=None):
self.code = code
self.status = status
self.detail = message
self.data = data if data else {}
def __str__(self):
return self.message
def custom_exception_handler(exc, context):
data = exc.data if hasattr(exc, "data") else {}
return JsonResponse(msg=exc.detail, status=exc.status_code, data=data, code=exc.status_code)
- 将该异常方法注册到rest_framework框架中 settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'libs.exceptions.custom_exception_handler',
}