Skip to content

Instantly share code, notes, and snippets.

@jpadilla
Created January 15, 2014 00:41
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jpadilla/8428798 to your computer and use it in GitHub Desktop.
Save jpadilla/8428798 to your computer and use it in GitHub Desktop.
Custom exception handler for Django Rest Framework that adds the `status_code` to the response and renames the `detail` key to `error`.
from rest_framework.views import exception_handler
def custom_exception_handler(exc):
"""
Custom exception handler for Django Rest Framework that adds
the `status_code` to the response and renames the `detail` key to `error`.
"""
response = exception_handler(exc)
if response is not None:
response.data['status_code'] = response.status_code
response.data['error'] = response.data['detail']
del response.data['detail']
return response
@mbi
Copy link

mbi commented Jul 7, 2014

Worth noting that the custom exception handler has to be activated in the settings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment