简体   繁体   English

如何在python中捕获任何异常并打印堆栈跟踪(DJANGO)

[英]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. 并将其放在settings.py中的MIDDLEWARE_CLASSES元组的第一位。

From middleware process_exception docs: 从中间件process_exception文档:

Django calls process_exception() when a view raises an exception. 当视图引发异常时,Django会调用process_exception() process_exception() should return either None or an HttpResponse object. process_exception()应该返回NoneHttpResponse对象。 If it returns an HttpResponse object, the template response and response middleware will be applied, and the resulting response returned to the browser. 如果它返回HttpResponse对象,则将应用模板响应和响应中间件,并将所得响应返回给浏览器。 Otherwise, default exception handling kicks in. 否则,将启动默认异常处理。

You might want to enable logging of all exceptions How do you log server errors on django sites 您可能想启用所有异常的日志记录如何在Django站点上记录服务器错误

and make a custom 500 django error page https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view 并制作一个自定义的500 django错误页面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. 并且您还应该在Web服务器级别(apache / nginx)创建一个500错误页面,以防框架无法正常工作。

That way you can "catch" all errors and show a nice error message to the client. 这样,您可以“捕获”所有错误,并向客户端显示一个不错的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM