Search code examples
pythondjangoexceptionhttpresponse

django: raise BadRequest as exception?


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

Solution

  • You need custom middleware to handle exception what you raise. Utilize custom exceptions to check for this condition in middleware.

    class ErrorHandlingMiddleware(object):
        def process_exception(self, request, exception):
            if not isinstance(exception, errors.ApiException): # here you check if it yours exception
                logger.error('Internal Server Error: %s', request.path,
                    exc_info=traceback.format_exc(),
                    extra={
                        'request': request
                    }
                )
            # if it yours exception, return response with error description
            try:
                return formatters.render_formatted_error(request, exception) # here you return response you need
            except Exception, e:
                return HttpResponseServerError("Error During Error Processing")