Handle Django server errors (5XX) in production to prevent showing sensitve information

I'm developing an API using Django Rest Framework. In the codes, there might be a lot of exceptional situations that we may not think of and cause 5XX errors. One approach to handle these errors is to put a try-exception in the whole function (Or places you guess an unknown error might occur). I want to show the details of the error in the API response (Not just in the logging server) when the debug mode is on in Django. Also, I want to hide these details in production mode (when debug is false) and just pass the error code with no body when the error is 5XX.

Is there any official (and efficient) way to do that? I was thinking of creating a middleware to handle that, but in this case, I should check all responses before passing the response to the user, and this is not efficient at all. I thought there might be a built-in function to handle this stuff, and I can override that to hide the body of the 5XX errors.

After seeing the additional information, you just need to add an if statement to decide what to put in the response body. This is what Django already does by default. Alternatively, just let Django do this for you and remove the try...except.

Original Answer:

I want to show the details of the error in the API response (Not just in the logging server) when the debug mode is on in Django. Also, I want to hide these details in production mode (when debug is false) and just pass the error code with no body when the error is 5XX.

You already answered your question. Setting DEBUG = True in settings.py will give an HTML response with the stack trace and other debugging information. Setting DEBUG = False, turns off this debugging information and does exactly as you say.

If you remove the try/except Django should just throw an error as normal - this will display details if settings.DEBUG, otherwise it will show an error template which you can customize to meet your needs. https://docs.djangoproject.com/en/4.0/topics/http/views/#customizing-error-views

Back to Top