My Django Rest Framework model views keep throwing Django's html pages to the client even if client sets "Accept: application/json". DRF seems to wrap in JSON only some exceptions by default. How can I prevent returning 30kb html pages (in Debug) if any exceptions occurs? Both in debug and production environments.
1 Answer
It sounds like you are talking about the Django error pages that it will generate for you when DEBUG is set to True and an unhandled exception is raised. Django REST framework will only handle specific exceptions for you and turn them into formatted responses, you can read more about exception handling in the DRF documentation.
If you are raising these errors yourself, you can change the base exception to be an APIException, which will then be transformed into a 400 error and formatted to the client. These are the same ones that you will usually see when you get a validation error.
If you are not the one raising these errors, you should look into catching them manually. DRF tries to proactively avoid errors, so if the error is coming because of a DRF call, I would recommend opening a ticket about it. Otherwise, you should be able to wrap it in a standard try...except block and re-raise the exception as an APIException so DRF formats it properly.
3 Comments
APIException, Http404, and PermissionDenied. DRF won't intercept other exceptions because they usually 1) reveal non-public information OR 2) aren't easily serializable. Because these would typically cause a 500 error anyway, DRF forces the developer to fix them by not intercepting them.urls.py, then enter some not existing address, and I see Django 404 page again.
?format=jsonas the query string, do you still get HTML pages back?