You implement an exception postprocessor by defining a process_exception (self, request, exception) function in the middleware class. The process_exception() function is called if an exception was raised by the view and was not handled.
By the Way
The process_exception() function is not called on Http404 exceptions.
The process_exception() function is passed the HttpRequest object and an Exception object arguments. Using the process_exception() function, you may be able to handle some exceptions and recover so that the browser doesn't receive an error. You can also use the process_exception() function to log and debug errors on the website.
The process_response() function can return None or an HttpResponse object. If None is returned, Django continues processing the exception using its built-in exception handling. If you pass back an HttpResponse object, the browser receives that response instead of an error.
For example, the following code snippet intercepts any unhandled exceptions and calls a HandleErrors() view function that returns some kind of HttpResponse:
from mySite.custom.views import HandleErrors class AddFooter(object): def process_exception(self, request, exception): return HandleErrors(request, exception)
Try It Yourself: Create and Install an Exception Postprocessor Middleware ApplicationIn this section, you will create and install an exception postprocessor application called CustomExceptionLogger. It will log information about exceptions that are not handled and, therefore, are sent to the browser. You will also define a new ExceptionEvent model in the Log application to store information about the exception before an error is sent back to the browser. You will also create a template that the view_log() view function will use to render the ExceptionEvent objects: Follow these steps to implement the exception postprocessor middleware application:
Listing 19.13. The ExceptionEvent Definition of the iFriends/Log/models.py File
Listing 19.14. The Imports and CustomExceptionLogger Definition of the django/middleware/custom.py File
Listing 19.15. Full Contents of the iFriends/templates/Custom/view_exception_log.py File
Listing 19.16. The view_log() View Function of the iFriends/Custom/views.py File
|