Reputation: 9431
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.
Upvotes: 4
Views: 3507
Reputation: 41671
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.
Upvotes: 3