4๐
โ
You may use exception middleware. See Django docs for more info.
Here is a sample implementation of the exception middleware:
class ExceptionHandlerMiddleware:
def __init__(self, get_response):
# if DEBUG is False we do not need this middleware
if not settings.DEBUG:
raise MiddlewareNotUsed
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_exception(self, request, exception):
if request.user.is_authenticated: #any custom logic based on request and/or exception
#returning None kicks in default exception handling
#i.e. it will show full debug info page if settings.DEBUG is True
return None
else:
#returning HttpResponse will force applying template response and response
#middleware and the resulting response will be returned to the browser
return HttpResponse('Something went wrong')
Since Django 3.1 you may also use a custom error reporter class by defining the DEFAULT_EXCEPTION_REPORTER setting. The custom error reporter class needs to inherit from django.views.debug.ExceptionReporter and you may override get_traceback_data() to implement custom logic. See Django docs for more info.
๐คdatosula
Source:stackexchange.com