Django自定义错误处理机制

本文介绍了在Django中自定义错误处理的两种方法:一是通过继承Exception创建自定义异常类,然后在视图中捕获;二是利用rest_framework的异常处理机制,通过继承APIException来定制错误信息。实践中发现,可以直接使用APIException来自定义异常,无需额外配置settings.py。示例展示了在注册功能中如何抛出自定义异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Django自定义错误处理机制

一、继承Exception错误处理机制

使用Exception错误处理机制。继承后,在View.py里面使用raise捕获异常,需要使用 [ try: exception 自定义的异常类 :]才能正常使用,不够灵活,使用方法如下:

#####  my_exception.py  ##### 

# 利用继承自定义异常提示信息
class MyException(Exception):
  def __init__(self, code, error, data):
    self.code = code
    self.error = error
    self.data = data
##### view.py ##### 

try:
  if not 1 < 0:
    raise MyException(1001, '你的说法错误', '1不小于0')
except MyException as e:
  pass

二、使用rest_framework的错误处理机制

查询了很多资料,都需要在settiong.py添加如下配置:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'common.restframework.xd_exceptions.custom_exception_handler', #这是使用自定制异常处理
}

并编辑自定义的异常处理函数

#####  xd_exceptions.py ##### 

from rest_framework.views import exception_handler
 
def custom_exception_handler(exc, context):
  # Call REST framework's default exception handler first,
  # to get the standard error response.
  response = exception_handler(exc, context)
 
  # Now add the HTTP status code to the response.
  if response is not None:
    response.data['status_code'] = response.status_code
    print(response.data)
    # response.data['message'] =response.data['detail']  #增加message这个key
    # response.data['message'] ='方法不对'  #增加message这个key
return response

通过本人实践,其实并不用以上两步,下面进入正题。

继承rest_framework.exceptions 的 APIException 自定义异常处理机制

#####  exceptions.py ##### 

"""自定义异常"""
from rest_framework.exceptions import APIException
from rest_framework import status


class BaseError(APIException):
    """自定义异常基础类"""

    def __init__(self, detail=None, status_code=status.HTTP_400_BAD_REQUEST):
        self.detail = detail  # 输出的错误信息,可以是字典型,也可以是字符串型
        self.status_code = status_code  # 响应的状态码
        
class DefaultError(BaseError):
    """默认异常,自定义使用,返回状态-1,响应状态400"""

    def __init__(self, message=None, code=-1):
        detail = {'code': code, 'message': message}  # 继承BaseError,传给self.detail
        super(DefaultError, self).__init__(detail)
#####  view.py ##### 

from rest_framework.views import APIView
class Register(APIView):  # 注意这里必须使用APIView,不能使用View,这里作者踩了坑
    @staticmethod
    def post(r):
        username = r.POST.get('username')
        password = r.POST.get('password')
        db_user = UserModels.objects.filter(username=username, password=password).first()
        if not db_user:
            msg = '用户名或密码错误'
            raise DefaultError()  # 这里就可以直接捕获并弹出异常
        return db_user.id
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值