Django - catch exception

前端 未结 4 487
灰色年华
灰色年华 2021-01-11 17:32

It might be a Python newbie question...

try:
   #do something
except:
   raise Exception(\'XYZ has gone wrong...\')

Even with DEBUG=True,

4条回答
  •  日久生厌
    2021-01-11 18:24

    If you want to get proper traceback and message as well. Then I will suggest using a custom middleware and add it to the settings.py middleware section at the end.

    The following code will process the exception only in production. You may remove the DEBUG condition if you wish.

    from django.http import HttpResponse
    from django.conf import settings
    import traceback
    
    
    class ErrorHandlerMiddleware:
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            response = self.get_response(request)
            return response
    
        def process_exception(self, request, exception):
            if not settings.DEBUG:
                if exception:
                    message = "{url}\n{error}\n{tb}".format(
                        url=request.build_absolute_uri(),
                        error=repr(exception),
                        tb=traceback.format_exc()
                    )
                    # Do whatever with the message now
                return HttpResponse("Error processing the request.", status=500)
    

提交回复
热议问题