Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - catch exception

Looking at this code:

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

Even with DEBUG=True, I don't want this raise Exception to give that yellow page, but it does.

I 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? 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?

like image 368
user423455 Avatar asked Jun 05 '12 01:06

user423455


2 Answers

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 %}
like image 147
simon Avatar answered Oct 09 '22 11:10

simon


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')
like image 20
Josh Smeaton Avatar answered Oct 09 '22 09:10

Josh Smeaton