How to capture middleware exception from other middleware in Django - python

I coding backend system with Django now, and I want control all exception from Django, so I create one middleware which name is CustomExceptoinMiddleware to control exception.
But sometimes other middleware also raise exception, I hope CustomExceptoinMiddleware can capture it too, but I don't know how to do it.
Can somebody help me?
Thanks in advance!
Python version: 3.7
Django version: 2.2.3
Setting.py
MIDDLEWARE = [
...
"api.core.middleware.CustomExceptoinMiddleware ",
"api.core.middleware.RaiseExcceptionMiddleware",
...
]
# middleware.py
class CustomExceptoinMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
print(f"Capture exception: {type(exception)}")
class RaiseExcceptionMiddleware(MiddlewareMixin):
def process_request(self, request):
raise KeyError()

You cannot do that. As you may read in documentation (https://docs.djangoproject.com/en/2.2/topics/http/middleware/#process-exception) you can only catch exception from the view. More detailed:
Again, middleware are run in reverse order during the response phase,
which includes process_exception. If an exception middleware returns a
response, the process_exception methods of the middleware classes
above that middleware won’t be called at all.

Related

Django - use middleware to block debug data on some cases

I'm using Django in debug mode in dev environment.
When some views fail, it returns the debug page (not debug_toolbar, just the page with list of installed apps, environment variables, stack trace, ...)
In my middleware, I have some cases (specific URLs, specific users, ...) where I want to remove this data and just return the raw response.
How should I do that?
currently my best idea is to just:
response.data = {}
return response
But I'm not sure if it's the proper way to do that, whether it covers all cases and so on. I just want to use a middleware to control in some cases and avoid the DEBUG mode for them.
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.

How to capture exception in django rest framework with django middleware?

Django middleware have a process_exception hook which can be used to capture exception and handler.
But there is some problem while using Django restframe work
class ExceptionHandler(MiddlewareMixin):
#staticmethod
def process_exception(request, exception):
if isinstance(exception, ValidationError):
return Response(data=exception.messages, status=status.HTTP_400_BAD_REQUEST)
For example, I try to use above middleware to capture the ValidationError and return HTTP 400
But it will not work and raise below error
AssertionError: .accepted_renderer not set on Response
It turns out that the rest-framework view layer will add a .accepted_renderer to the response.
If I handle the exception outside view. This attribute will be missed and cause another exception.
So my question is: Is it wrong to handle exception in middleware when using django rest-framework?
What is the correct way to do ?
A better way to do this in Django Rest framework is to create a custom exception handler and replace the default exception handler with your custom handler. For more details on it you can check out the official documentation: http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

Django middleware catches exception

I am using python-social-auth, and I am catching any exceptions using the following middleware:
class ExtendedSocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
def process_exception(self, request, exception):
if hasattr(social_exceptions, exception.__class__.__name__):
return HttpResponse('error')
else:
raise exception
What I would like to do in this exception handler is redirect the user to the page they came from, and display the exception in a label in that template. How would I do this?
As documented here :
return redirect(url)

How to catch any exception in python and print stack trace (DJANGO)

I have like this:
try:
#bunch of code
except:
return HttpResponse....
I want to send an error to client and to print stack trace on console. How can i do that?
You can do something like this
import traceback
from django.http import HttpReponse
def view(request):
try:
#throw exception
except:
tb = traceback.format_exc()
return HttpResponse(tb)
# normal flow
You can create a custom middleware class where you can catch all exceptions:
class ErrorMiddleware(object):
def process_exception(self, request, exception):
# send error
return HttpResponse(...) # or None
and put it on first place to MIDDLEWARE_CLASSES tuple in settings.py.
From middleware process_exception docs:
Django calls process_exception() when a view raises an exception.
process_exception() should return either None or an HttpResponse
object. If it returns an HttpResponse object, the template response
and response middleware will be applied, and the resulting response
returned to the browser. Otherwise, default exception handling kicks
in.
You might want to enable logging of all exceptions How do you log server errors on django sites
and make a custom 500 django error page https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view
and you should also make a 500 error page at web server level (apache / nginx) just in case the framework doesn't work.
That way you can "catch" all errors and show a nice error message to the client.

Disable Django exception formatting

I'm calling Django from within another application.
While debugging, if a Django exception occurs, the (html) response body is being picked up and then wrapped in an exception generated in the calling app.
This makes it a real pain to determine what the problem was as I need to wade through CSS, Html, Js, etc.
Is there any way to get Django to only output an exception message and a stack trace as plain text?
You can write your own exception-handling middleware class. See the documentation for the process_exception middleware method:
process_exception(self, request, exception)
request is an HttpRequest object. exception is an Exception object raised by the view function.
Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in.
So I think you need to write something like this:
import traceback
from django.http import HttpResponse
class PlainTextExceptionMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse(traceback.format_exc(), "text/plain")
and then add the class to your MIDDLEWARE_CLASSES setting.
Just set the DEBUG_PROPAGATE_EXCEPTIONS in your settings:
If set to True, Django’s normal exception handling of view functions
will be suppressed, and exceptions will propagate upwards. This
can be useful for some test setups, and should never be used on a live site.
See the Django docs

Categories