Tuesday, 2 January 2024

python module, django how to set up custom exception handler to return custom exceptions

 python module

__init__.py

https://stackoverflow.com/questions/448271/what-is-init-py-for


mydir/spam/__init__.py
mydir/spam/module.py

and mydir is on your path, you can import the code in module.py as

import spam.module

or

from spam import module

----
module
https://www.w3schools.com/python/python_modules.asp

Create a Module
To create a module just save the code you want in a file with the file extension .py:

ExampleGet your own Python Server
Save this code in a file named mymodule.py

def greeting(name):
  print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")


---------------------------------------

django official documentation on how to set up custom exception handling :

https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling



django example of setting up custom exception handling :


api_exceptions.py

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException

custom_exception_handler

def custom_exception_handler(exc, context):

    response = exception_handler(exc, context)

    if response is not None:
        response.data['status_code'] = response.status_code

        #replace detail key with message key by delete detail key
        response.data['message'] = response.data['detail']
        del response.data['detail']

    return response

(*!note both custom_exception_handler, and CustomApiException should in api_exceptions.py 
and custom_exception_handler is good enough )

CustomApiException

class CustomApiException(APIException):

    #public fields
    detail = None
    status_code = None

    # create constructor
    def __init__(self, status_code, message):
        #override public fields
        CustomApiException.status_code = status_code
        CustomApiException.detail = message

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utilities.helpers.api_exceptions.custom_exception_handler',
}

(!note path should module.file_name.function_name, or module.folder.file_name.fucntion_name,
for folder it has to have __init__.py, and module need to be added in INSTALLED_APPS 
in settings.py)

your_view.py

raise CustomApiException(333, "My custom message")

#json response
{
  "status_code": 333,
  "message": "My custom message"
}

No comments:

Post a Comment