10

看这段代码:

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

即使使用DEBUG=True,我也不希望它raise Exception给出那个黄页,但它确实如此。

我想通过将用户重定向到错误页面或显示错误来处理异常(在页面顶部给出 CSS 错误消息......)

我该如何处理?如果我简单地提出它,我会得到黄色的调试页面(同样,我不希望某些异常通过在 DEBUG=True 时显示调试页面来阻止站点运行)。

如何在views.py 中处理这些异常?

4

4 回答 4

21

你在这里有三个选择。

  1. 提供404 处理程序或 500 处理程序
  2. 在代码中的其他地方捕获异常并进行适当的重定向
  3. 提供自定义中间件与process_exception实现

中间件示例:

class MyExceptionMiddleware(object):
    def process_exception(self, request, exception):
        if not isinstance(exception, SomeExceptionType):
            return None
        return HttpResponse('some message')
于 2012-06-05T01:16:54.477 回答
4

您可以引发 404 错误或简单地将用户重定向到带有错误消息的自定义错误页面

from django.http import Http404
#...
def your_view(request)
    #...
    try:
        #... do something
    except:
        raise Http404
        #or
        return redirect('your-custom-error-view-name', error='error messsage')
  1. Django 404 错误
  2. Django 重定向
于 2012-06-05T01:16:12.107 回答
1

另一个建议是使用Django 消息传递框架来显示 flash 消息,而不是错误页面。

from django.contrib import messages
#...
def another_view(request):
    #...
    context = {'foo': 'bar'}
    try:
        #... some stuff here
    except SomeException as e:
        messages.add_message(request, messages.ERROR, e)

    return render(request, 'appname/another_view.html', context)

然后在 Django 文档中的视图中:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
于 2016-10-25T08:48:39.963 回答
1

如果您还想获得适当的回溯和消息。然后我会建议使用自定义中间件并将其添加到最后的 settings.py 中间件部分。

以下代码将仅在生产中处理异常。如果您愿意,可以删除 DEBUG 条件。

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)
于 2020-01-24T12:31:44.207 回答