郑文峰的博客 郑文峰的博客
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)

zhengwenfeng

穷则变,变则通,通则久
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)
  • python

    • 基础

    • 第三方库

    • django

      • django celery 结合使用
      • django rest_framework使用jwt
      • django rest_framework Authentication
      • django rest_framework异常处理
        • 简介
        • 操作
      • django rest_framework 自定义文档
      • django压缩文件下载
      • django rest_framework使用pytest单元测试
      • django restframework choice 自定义输出数据
      • django Filtering 使用
      • django viewset 和 Router 配合使用时报的错
      • django model的序列化
      • django中使用AbStractUser
      • django.core.exceptions.ImproperlyConfigured Application labels aren't unique, duplicates users
      • django 中 media配置
      • django 外键引用自身和on_delete参数
      • django 警告 while time zone support is active
      • django rest_framework 分页
    • flask

    • tornado

    • 其他

  • go

  • 其他

  • 编程
  • python
  • django
zhengwenfeng
2022-08-10
目录

django rest_framework异常处理

# 简介

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

# 操作

  1. 自定义json返回的格式

libs/response.py

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)
1
2
3
4
5
6
7
8
9
10
11
  1. 自定义全局的异常处理方法 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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  1. 将该异常方法注册到rest_framework框架中 settings.py
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'libs.exceptions.custom_exception_handler',
}
1
2
3
#python#django
上次更新: 2023/01/15, 15:47:48
django rest_framework Authentication
django rest_framework 自定义文档

← django rest_framework Authentication django rest_framework 自定义文档→

最近更新
01
django rest_framework 分页
03-20
02
学习周刊-第03期-第09周
03-03
03
学习周刊-第02期-第08周
02-24
更多文章>
Theme by Vdoing | Copyright © 2022-2023 zhengwenfeng | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式