1

I'm using a custom exception handler for my REST API, which responds with JSON data that my front end knows how to handle. The problem is that with the setting DEBUG = True, Django doesn't use my custom exception handler. Instead, it responds with the standard HTML debug page, like this:

Here's the default response with DEBUG = True

Here's my settings.py:

DEBUG = True

REST_FRAMEWORK = {
   # This doesn't seem to do anything when DEBUG == True
   'EXCEPTION_HANDLER': 'stripe_app.utils.custom_exception_handler'
}
...

I know that I could just set DEBUG = False, but if I did that I'd also have to change many other things that use the DEBUG variable.

So, How can I use my custom exception handler with the DEBUG = True setting?

I've already looked for answers in the DRF docs: https://www.django-rest-framework.org/api-guide/settings/#exception_handler

and the Django docs: https://docs.djangoproject.com/en/3.1/ref/settings/#debug

but I can't find the answer I'm looking for.

EDIT

I just realized that I forgot to set the following in my root urls.py, per the DRF docs:

handler400 = 'stripe_app.views.bad_request'
handler500 = 'stripe_app.views.server_error'

However, DEBUG = True still causes problems. For example, even if I created a view like this:

def always_raise_exception(request):
    raise Exception

If DEBUG == True, the above view responds with the standard Django HTML debug page.

If DEBUG == False, it responds (correctly) with a JSON response (another edit: I think this is just because the server server raised a different exception than with DEBUG = True).

1 Answer 1

2

Are you sure that with DEBUG=False, exception handler is being used?

From the documentation:

Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

From your example, I guess you didn't explicitly raise 404, so exception handler is avoided.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you are right. Setting EXCEPTION_HANDLER in settings.py still gives me properly formatted responses for validation errors. I was hoping I could find an easy way to format all of my error responses in a certain way. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.