SoFunction
Updated on 2025-03-02

Django solves the problem of developing custom throw exceptions

During the development process, we should verify data on the backend for illegal information entered by the user and throw relevant exceptions to pass them to the frontend to prompt the user.

But how to customize the exception throwing information? There are usually three methods of processing, and I will introduce these three methods in turn.

The first method:

This method is the simplest. You only need to create a dictionary object and pass it to the front end through render.

The dictionary object is as follows:

result = {'code':'', 'message':''}
render(request, '', result:result)

The second method:

You need to inherit the Exception class, the code is as follows:

# Use inheritance custom exception prompt informationclass MyException(Exception):
  def __init__(self, code, error, data):
     = code
     = error
     = data
try:
  if not 1 < 0:
    raise MyException(1001, 'Your statement is wrong', '1 is not less than 0')
except MyException as e:
  pass

The third method:

Customize a class that inherits object

class MyTest(object):
  def __init__(self):
    # Custom status code     = 1000
     = ''
     = ''
 
  @property
  def dict(self):
    return self.__dict__

When you need to customize the exception, create an object and formulate relevant information.

# Create an instance objectone = MyTest()
 = 1001
 = 'You were wrong'
 = 'Please check again'
 
print()

To sum up, these are three methods that I often use to verify data on the backend and throw relevant exception information.

Supplementary knowledge:Django rest framework custom exception handling

1.

Configurations to be added in

Add 'rest_framework' to the app,

2. Add this configuration in settings

REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'.xd_exceptions.custom_exception_handler', #This is using custom exception handling
}

xd_exceptions.py here is the exception handling function

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:
    ['status_code'] = response.status_code
    print()
    # ['message'] =['detail'] #Add message this key    # ['message'] ='The method is incorrect' #Add message this key
  return response

Custom exception class When an exception is actively thrown, an exception of the following type can be thrown.

my_errors.py

from rest_framework import status
from rest_framework.exceptions import APIException
from  import xd_status

# class ParseError(APIException):
#   status_code = xd_status.HTTP_400_BAD_REQUEST
# default_detail = 'This is.default_detail========'#   default_code = 'parse_error'
#

class XdError(APIException):
  pass

class ParamError(XdError):
  status_code = 400

class Unauthorized(XdError):
  status_code = 401

class PermissionDenied(XdError):
  status_code = 403

class ObjectNotFound(XdError):
  status_code = 404

class ServerError(XdError):
  status_code = 500

class ErrorCode:
  UNAUTHORIZED = 10000 # Not logged in  PERMISSION_DENIED = 10001 # No permissions  PARAM_ERROR = 40000 # Parameter verification error  DATA_NOT_FOUND = 40001 # No data found  DATA_NOT_VALID = 40002 # Data Error  REPEAT_POST = 40003 # Repeat submission  EEEE = 40003 # New error

Actively throw exceptions in view or function.

class SupserUserDetailView(APIView):
  # authentication_classes = []
  permission_classes = [SupserPermisson,]

  def put(self,request,pk):
    if not .is_superuser:
      if  != pk:
        raise ParamError('The user does not have permission to modify', )  #This is to throw a custom exception, and then you can catch this exception by your own exception catching method.    user = (id=pk)
    if not user:
      raise ParamError('The modified user does not exist', )
    data = handel_c_user()
    user_obj = Creat_newuser_serializers(data=data, instance=())

    if user_obj.is_valid():
      user_obj.save()
      res={'status':"Modification was successful"}

      return JsonResponse(data=res, code=200, desc="success", status=status.HTTP_200_OK)
    res = {'status':user_obj.errors}

    return JsonResponse(data=res,code=200,desc="success",status=status.HTTP_200_OK)

Workflow

Access trigger exception

Automatically throw a custom exception

Custom exception catching function catches exception and returns user-friendly data to the front end

The above article Django solves the problem of throwing exceptions in developing custom development is all the content I share with you. I hope you can give you a reference and I hope you can support me more.