I'm trying to setup email error logging and I want to test it.
Whats an easy way to trigger a 500 error in Django? This surprisingly has not been discussed here yet.
When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.
Open your settings.py file (or settings_local.py ) and set DEBUG = False (just add that line if necessary). Turning off the Django debug mode will: Suppress the verbose Django error messages in favor of a standard 404 or 500 error page. You will now find Django error messages printed in your arches.
A test view like this will work:
from django.http import HttpResponse def my_test_500_view(request): # Return an "Internal Server Error" 500 response code. return HttpResponse(status=500)
or use the baked in error class:
from django.http import HttpResponseServerError def my_test_500_view(request): # Return an "Internal Server Error" 500 response code. return HttpResponseServerError()
Raising an appropriate Exception
is the most robust way to test this. Returning an HttpResponse
of any variety, as in @agconti 's answer, will not allow you to test the behavior of error handling. You'll just see a blank page. Raising an exception triggers both the correct response code and the internal Django behavior you expect with a "real" error.
Response code 500 represents the server not knowing what to do. The easiest way is to write into your test or test-view raise Exception('Make response code 500!')
.
Most other errors should be raised with exceptions designed to trigger specific response codes. Here's the complete list of Django exceptions that you might raise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With