有没有办法在django python中捕获500个错误?

有没有办法在django python中捕获500个错误?,python,django,http,django-middleware,Python,Django,Http,Django Middleware,我想捕获500个异常并返回一个HTTP4xx异常。使用“Exception Exception”将捕获所有不需要的异常。我想知道有没有办法只捕捉500个错误 try: <code> except <Exception class>: return http 404 reponse 试试看: 除: 返回http 404响应 我搜索了很多,但不知道怎么做。提前感谢我不确定返回404而不是500是一个好主意,但您可以通过定义500个错误的值来实现这一点 在您的

我想捕获500个异常并返回一个HTTP4xx异常。使用“Exception Exception”将捕获所有不需要的异常。我想知道有没有办法只捕捉500个错误

try:
   <code>
except <Exception class>:
   return http 404 reponse
试试看:

除:
返回http 404响应

我搜索了很多,但不知道怎么做。提前感谢

我不确定返回404而不是500是一个好主意,但您可以通过定义500个错误的值来实现这一点

在您的URL.py中:

handler500 = 'mysite.views.my_custom_error_view'
在your views.py中:

from django.http import HttpResponse

def my_custom_error_view(request):
    """
    Return a 404 response instead of 500.
    """
    return HttpResponse("error message", status_code=404)

我想你需要,没有例外。WSGI处理程序捕获任何异常并返回500响应(如果有),保存一些特殊情况,例如
Http404
PermissionDenied
。那么我应该使用exception:?那是唯一的办法吗@克威尔,我不确定你到底想要什么,所以我不能对此发表评论。