django: raise BadRequest as exception?

guettli picture guettli · Aug 21, 2014 · Viewed 30.3k times · Source

Is it possible to raise BadRequest as exception in django?

I have seen that you can raise a 404 [1].

Use case: in a helper method I load a json from request.GET. If the json was cut since the browser (IE) cut the url, I would like to raise a matching exception.

A BadRequest exception looks appropriate, but up to now there seems to no such exception in django.

In 1.6 there is a SuspiciousOperation exception. But this does not match in my case, since it is not security related.

Of course I could put a try..except around my helper method in the view method, but this is not DRY.

Has someone a solution where I don't need a try..exception around every call of my helper method?

[1] https://docs.djangoproject.com/en/1.6/ref/exceptions/#django.core.urlresolvers.Resolver404

Update

Code example:

def my_view(request):
    data=load_data_from_request(request) # I don't want a try..except here: DRY
    process_data(data)
    return django.http.HttpResponse('Thank you')

def load_data_from_request(request):
    try:
        data_raw=json.loads(...)
    except ValueError, exc:
        raise BadRequest(exc)
    ...
    return data

Answer

yprez picture yprez · Nov 8, 2014

The other answers are explaining how to return an HTTP response with 400 status.

If you want to hook into Django's 400 error handling, you can raise a SuspiciousOperation exception or a subclass of it.

See the docs here and here.

In your example it would look like:

from django.core.exceptions import SuspiciousOperation

def load_data_from_request(request):
    try:
        data_raw = json.loads(...)
    except ValueError:
        raise SuspiciousOperation('Invalid JSON')
    # ...
    return data