Should unrecoverable exceptions from HTTP parameter problems be caught?
|March 11, 2014||Posted by forumadmin under TechQns||
Is it necessary to catch errors stemming from HTTP inputs? Is it ever a good idea to let it fail naturally (allow the exception to bubble up)?
I have a Django view for a server side interface for an AJAX call that looks something like this:
def some_view(request): try: some_int = int(request.POST.get('some_int')) # May raise ValueError or TypeError except (ValueError, TypeError): return HttpResponseBadRequest('some_int must be an int') # ... Code that assumes some_int is an int return HttpResponse('The normal response')
Is it ever acceptable in production code to have something like this?
def some_view(request): some_int = int(request.POST.get('some_int')) # Ignore ValueError or TypeError raised # ... Code that assumes some_int is an int return HttpResponse('normal_response')
As I accept more parameters, I find that it is frustrating to maintain so many try/except blocks which are mostly the same and I end up with a ton of boiler plate code.
Of course I tried to refactor this into a separate function but since Django requires an
HttpResponse to be returned, not raised as an exception, I can’t plug it into a view without a try/except block. Also, conversions to int aren’t the only thing I check… there are a lot of business logic sanity checks performed depending on the input as well. For example, I would validate that the JSON passed is of a specific format (i.e. array of objects of int array, etc.).
My views end up being 70+ lines of code just for sanity checks and a few lines of code that actually generate the response. Somehow I feel like there should be a more elegant way but I haven’t found one so I’m considering forgoing all checks and just letting Django take care of it. Is this a bad idea?
I’m aware of the following potential problems if I don’t catch the exceptions:
- The same HTTP 500 is returned for all errors
- If logging is enabled in production, it would probably log an error every time an invalid input occurs
Are there other problems I should be aware of? It just feels wrong not to catch exceptions from user inputs even though there’s not much I can do about it in terms of recovery logic.
|Asked By – user193130||Read Answers|