博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django rest_framework 异常
阅读量:3708 次
发布时间:2019-05-21

本文共 1442 字,大约阅读时间需要 4 分钟。

简介

当程序中出现异常时,我们想要返回的是包含异常信息的json数据。返回正常的信息和异常信息的格式一致化。

操作

  1. 自定义json返回的格式

libs/response.py

from rest_framework.response import Responseclass 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)
  1. 自定义全局的异常处理方法
    libs/exceptions.py
from rest_framework import statusfrom rest_framework.views import exception_handlerfrom libs.response import JsonResponseclass 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.messagedef 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)
  1. 将该异常方法注册到rest_framework框架中
    settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'libs.exceptions.custom_exception_handler',}

转载地址:http://yakjn.baihongyu.com/

你可能感兴趣的文章
Java中List、Map、Set三个接口,存取元素时,各有什么特点?
查看>>
客户端与服务器(C/S架构与B/S架构)、AJax学习
查看>>
jsp中String path = request.getContextPath()的作用
查看>>
登录界面验证码的实现
查看>>
EL表达式
查看>>
Javaweb MVC设计模式、Modle发展史、项目分层和三层架构
查看>>
HTML表格和HTML表单
查看>>
JSP访问数据库,Session对象和九大内置对象
查看>>
Springboot分层图解
查看>>
并查集(Disjiont Set)
查看>>
Java操作HBase
查看>>
Linux编程考前测试题
查看>>
Openstack面试题和知识点总结
查看>>
C++ 实例化一个对象
查看>>
基于Spring boot+Vue的在线考试系统
查看>>
大数据学习路线
查看>>
前端学习路线
查看>>
推荐几个单机游戏下载网、高质量图片下载网
查看>>
数据库查询
查看>>
单臂路由配置
查看>>