背景
有时候需要重写序列化类的create
方法或update
方法。那么当逻辑进入异常时,我们不希望直接抛出系统异常,而是返回自定义异常响应给前端,以便于前端显示。
步骤
- 创建工具类
utils.py
,继承APIException
- 创建工具类
from rest_framework.exceptions import APIException
class ParamsException(APIException):
"""
serializers自定义错误响应
"""
def __init__(self, error):
self.detail = error
- 2、在对应app的
serializers.py
中这样进行调用,例如:
from rest_framework import serializers
from .models import Envs
from utils.drf_utils import ParamsException
class EnvSerializer(serializers.ModelSerializer):
class Meta:
model = Envs
exclude = ('create_time', 'is_delete')
ex_kwargs = {
'update_time': {
'read_only': True
}
}
def create(self, validated_data):
"""
判断名字是否已存在再进行创建(逻辑删除视为不存在)
:param validated_data:
:return:
"""
if not Envs.objects.filter(name=validated_data['name'], is_delete=False).count():
return super().create(validated_data)
else:
raise ParamsException({'code': 2001, 'msg': '名称已存在'})
- 3.对应的
model.py
from django.db import models
from utils.base_models import BaseModel
class Envs(BaseModel):
id = models.AutoField(primary_key=True, verbose_name='主键', help_text='主键')
name = models.CharField(max_length=120, verbose_name='环境名称', help_text='环境名称')
desc = models.CharField(max_length=800, null=True, blank=True, verbose_name='环境描述', help_text='环境描述')
host = models.URLField(max_length=200, verbose_name='环境host', help_text='环境host')
class Meta:
db_table = 'pf_envs'
verbose_name = '环境表'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
-
4.发出请求以及结果
请求参
结果
DRF自带的错误提示
raise serializers.ValidationError('xxxx')
from rest_framework import serializers
from .models import Envs
from utils.drf_utils import ParamsException
class EnvSerializer(serializers.ModelSerializer):
class Meta:
model = Envs
exclude = ('create_time', 'is_delete')
ex_kwargs = {
'update_time': {
'read_only': True
}
}
def create(self, validated_data):
"""
判断名字是否已存在再进行创建(逻辑删除视为不存在)
:param validated_data:
:return:
"""
if not Envs.objects.filter(name=validated_data['name'], is_delete=False).count():
return super().create(validated_data)
else:
serializers.ValidationError('名称已存在')
-
结果:
提示内容
网友评论