Django Globally handling exception


Say you have implemented some logic to detect attempts to modify an object in the database while the client that submitted changes didn't have the latest modifications. If such case happens, you raise a custom exception ConfictError(detailed_message).

Now you want to return an HTTP 409 (Confict) status code when this error occurs. You may typically use as middleware for this instead of handling it in each view that might raise this exception.

class ConfictErrorHandlingMiddleware:
    def process_exception(self, request, exception):
        if not isinstance(exception, ConflictError):
            return  # Propagate other exceptions, we only handle ConflictError
        context = dict(confict_details=str(exception))
        return TemplateResponse(request, '409.html', context, status=409)