Viewing error stacktrace on 500 as json on django

1k views Asked by At

Using django rest framework, I'm always making API calls through tests. But sometimes they fail and I am currently logging the HTML with the stacktrace to a file and then viewing it with a browser, but this is very annoying.

Is there a way to make it output json or anything else besides html?

1

There are 1 answers

0
Alex T On

DRF only handles the following: (source: DRF docs)

  • Subclasses of APIException raised inside REST framework.
  • Django's Http404 exception.
  • Django's PermissionDenied exception.

If you know which view this is happening, one way of making it render API responses would be to try/except and raise it as an APIException instead of whatever you are actually getting.

Alternately you can also provide your own Exception Handler (see https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/views.py#L52 for the original) which handles more than the default 3 exception types, by using the EXCEPTION_HANDLER setting for REST_FRAMEWORK

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