Catch all exceptions in django rest framework

I guess this is more of a code quality question but it does involve handling unhandled exceptions is Django rest framework.

Deleting a protected record just return <h1>500 internal server error<h1> So I added the example custom exception handler. The first line returns a response that is none.

response = exception_handler(exc, context)

from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None:
        #DRF could not process the exception so we will treat it as a 500 and try to get the user as much info as possible.
        response = Response({'error': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

return response

So in this case I am treating it as a 500 because the DRF couldn't handle the exc.

I guess my question is is this an appropriate way to handle it and does anyone have experience with this have a better solution?

1 answer

  • answered 2018-02-13 02:50 Alvin

    You can use the Django REST Framework exceptions

    In your specific case you'd probably want to use NotFound

    from rest_framework.exceptions import NotFound
    # something bad happens
    raise NotFound('User Message')

    NotFound will throw a 404 error by default, to raise a 500 you could add.

    raise NotFound('User Message', code=500)

    The other exceptions are used the same way.