Location for Django Rest framework exception handler

Viewed 2606

The DRF Docs say that once an exception handler is set up, it needs to be defined in the settings.py as follows:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

My Django project layout is like this:

backend
    settings.py
    connectivity_service
        utils
            Custom404ErrorMessage.py

The project is called backend and the app name is connectivity_service.The Custom404ErrorMessage.py file contains the function custom_exception_handler which handles the exception.

My settings.py looks like this:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'backend.connectivity_service.utils.Custom404ErrorMessage'
}

However, this gives me the following error message:

ImportError: Could not import 'backend.connectivity_service.utils.Custom404ErrorMessage' 
for API setting 'EXCEPTION_HANDLER'. ModuleNotFoundError: No module named 
'backend.connectivity_service'.

What am i doing wrong ?

2 Answers

I had this problem too and what you need to do to solve is this:

  1. create utils.py inside your app folder
  2. define your custom_exception_handler function inside it
  3. in your setting file add this " 'EXCEPTION_HANDLER': 'my_app.utils.custom_exception_handler' ", no need to type my_project

My guess is that you confused the text when translating from the DRF example to your code. The docs state:

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

return response

Then it tells you to add it to your settings as:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

Keep in mind that the example above has the following folder structure:

my_project > my_app > utils > custom_exception_handler

Which translates to:

my_project_FOLDER > my_app_FOLDER > utils.PY > NAME_OF_DEFINED_FUNCTION_THAT_HANDLES_EXCEPTIONS

That's how I think you might have gotten confused. So you have Custom404ErrorMessage.py inside a utils_FOLDER and are trying to import that instead of the defined function itself. Unless of course that Custom404ErrorMessage.py is a class, but I doubt it since you seemed to be following the linked DRF example which uses a function.

I assume that your Custom404ErrorMessage.py has the following:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
....

So for your set up, your settings.py would look like this:

REST_FRAMEWORK = {
 'EXCEPTION_HANDLER': 'backend.connectivity_service.utils.Custom404ErrorMessage.custom_exception_handler'
 }

See how the last part is the defined function? Hope that helps!

Related