@Jasper_Holton's profile photo

Verbose Error Handling With Django Middleware This is a simple way to verbosely handle errors using Django middleware. Using this middleware, you can render your error tracebacks to custom HTML pages, instead of using the Django debug mode error pages. Here is how the code works. First, some middleware to get the current error in the error handler view.

# app/middleware.py
from threading import local 
import traceback 
from django.utils.deprecation import MiddlewareMixin

_error = local() # Store the error in a local

class ExceptionVerboseMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception): # Process the exception
        _error.value = traceback.format_exc() # Store the stack trace from traceback

def get_current_exception(): # Return the error
        return _error.value
    except AttributeError:
        return None
In the views, add a call to the middleware to get the exception.
# app/views.py
def handler500(request):
    data = {'title':'Error 500', 'error': get_current_exception()} # Put the error in the context, so we can render it to the template.
    return render(request,'blog/500.html', data)
Include this middleware in your settings.py file.
# project/settings.py
And finally, add this line to your projects urls.py
# project/urls.py
handler500 = 'blog.views.handler500'
Now, you simply need to add a tag,
{{ error }}
, to render your error to the error 500 page. This is all it takes to set up a verbose error handling page in Django.

Pinterest logo
Tumblr logo VK logo

https://uglek.com/post/421/ -

© Uglek, 2022

Terms of Use and Privacy Policy