5

I have like this:

try:
    #bunch of code
except:
    return HttpResponse....

I want to send an error to client and to print stack trace on console. How can i do that?

milandjukic88
  • 1,065
  • 3
  • 13
  • 30

3 Answers3

9

You can do something like this

import traceback 
from django.http import HttpReponse

def view(request):
     try:
          #throw exception
     except:
         tb = traceback.format_exc()
         return HttpResponse(tb)
    # normal flow
Serafeim
  • 14,962
  • 14
  • 91
  • 133
5

You can create a custom middleware class where you can catch all exceptions:

class ErrorMiddleware(object):
    def process_exception(self, request, exception):
        # send error
        return HttpResponse(...) # or None

and put it on first place to MIDDLEWARE_CLASSES tuple in settings.py.

From middleware process_exception docs:

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.

ndpu
  • 22,225
  • 6
  • 54
  • 69
2

You might want to enable logging of all exceptions How do you log server errors on django sites

and make a custom 500 django error page https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view

and you should also make a 500 error page at web server level (apache / nginx) just in case the framework doesn't work.

That way you can "catch" all errors and show a nice error message to the client.

Community
  • 1
  • 1
jperelli
  • 6,988
  • 5
  • 50
  • 85