Skip to content

Instantly share code, notes, and snippets.

@aman0511
Forked from jpadilla/exceptions.py
Created July 11, 2016 10:12
Show Gist options
  • Select an option

  • Save aman0511/251b9a106575a5301f06bfc043276c9d to your computer and use it in GitHub Desktop.

Select an option

Save aman0511/251b9a106575a5301f06bfc043276c9d 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment