项目开发管理最佳实践之一 --定义异常类exceptions
项目开发中,经常遇到需要抛出异常情况,可以根据项目存在情况定一个异常类,项目以django ,rest_framework为例
1 rom django.db.models.deletion import ProtectedError 2 from rest_framework.exceptions import APIException 3 from django.db.utils import IntegrityError 4 from rest_framework import status 5 ''' 6 定义抛出异常 7 ''' 8 class AuthenticationFailed(APIException): 9 status_code = status.HTTP_400_BAD_REQUEST 10 default_detail = '身份验证失败' 11 default_code = 'authentication_failed' 12 class NotAuthenticated(APIException): 13 status_code = status.HTTP_401_UNAUTHORIZED 14 default_detail = '未通过身份验证' 15 default_code = 'not_authenticated' 16 17 class ValidationError(APIException): 18 status_code = status.HTTP_400_BAD_REQUEST 19 default_detail = '无效请求' 20 default_code = 'invalid' 21 22 class ParseError(APIException): 23 status_code = status.HTTP_400_BAD_REQUEST 24 default_detail = '格式错误' 25 default_code = 'parse_error' 26 27 class PermissionDenied(APIException): 28 status_code = status.HTTP_403_FORBIDDEN 29 default_detail = '无权限执行操作.' 30 default_code = 'permission_denied' 31 32 class NotFound(APIException): 33 status_code = status.HTTP_404_NOT_FOUND 34 default_detail = '数据不存在' 35 default_code = 'not_found' 36 37 class ServerError(APIException): 38 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR 39 default_detail = '服务器错误' 40 default_code = 'server_error' 41 42 __all__ = [ 43 'ProtectedError', 'IntegrityError', 'AuthenticationFailed', 'NotAuthenticated','ValidationError', 'ParseError', 44 'PermissionDenied', 'NotFound', 'ServerError']

浙公网安备 33010602011771号