Django - catch exception

非 Y 不嫁゛ 提交于 2020-01-02 02:20:10

问题


It might be a Python newbie question...

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

Even with DEBUG=True, I don't want this raise Exception gives me that yellow page. I actually want to handle the exception by redirecting users to an error page or shows the error (give a CSS error message on the top of the page...)

How do I handle that? Can someone guide me? If I simply raise it, I will get yellow debug page (again, I don't want certain exceptions to stop the site from functioning by showing the debug page when DEBUG=True).

How do I handle these exceptions in views.py?

Thanks.


回答1:


You have three options here.

  1. Provide a 404 handler or 500 handler
  2. Catch the exception elsewhere in your code and do appropriate redirection
  3. Provide custom middleware with the process_exception implemented

Middleware Example:

class MyExceptionMiddleware(object):
    def process_exception(self, request, exception):
        if not isinstance(exception, SomeExceptionType):
            return None
        return HttpResponse('some message')



回答2:


You can raise a 404 error or simply redirect user onto your custom error page with error message

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 error
  2. Django redirect



回答3:


Another suggestion could be to use Django messaging framework to display flash messages, instead of an error page.

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)

And then in the view as in Django documentation:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}


来源:https://stackoverflow.com/questions/10890368/django-catch-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!