Django - catch exception

前端 未结 4 408
灰色年华
灰色年华 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:22

    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 %}
    
      {% for message in messages %} {{ message }} {% endfor %}
    {% endif %}

提交回复
热议问题