3

I am using django 1.2.7 and python 2.6. If I use this code: (with an identation error on porpuse)

def myview(request):
    try:
        if x:
        print 'x'
    except:
        return HttpResponseServerError('bazinga')

then I don't get my response. I get django 500 response.

but if I change the code to this:

  def myview(request):
    try:
        if x:
            print 'x'
    except:
        return HttpResponseServerError('bazinga')

now I get my own 500 with the bazinga written.

How can I catch the identation error in the first example ?

Just as my try-except catch the exception in the 2nd example.

Lain
  • 2,166
  • 4
  • 23
  • 47
yossi
  • 12,945
  • 28
  • 84
  • 110

4 Answers4

5

Don't try to make Django return a nice response in the case of a syntax error. That will be difficult, and will involve having code of your own just for this case, and that code itself will need to be error-free, etc.

Instead, put that effort into an automated test suite that will make it easy to find those errors before you deploy your code.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
2

Syntax errors can be detected trivially as you don't need to run the code but only to import it.

There's no reason you should try to catch them, just fix them.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
0

You can catch syntax (And Indentation) errors out of your code. Look here for more info: How to catch IndentationError

Community
  • 1
  • 1
Vasisualiy
  • 750
  • 5
  • 19
0

Syntax errors are not run time errors, they occur at compile time. As far as I know, you can't catch them with a try/except block.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895