In pyramid how to return 400 response with json data?

Viewed 8863

I have the following jquery code:

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    statusCode: {
        200: function (data, textStatus, jqXHR) {
                console.log(data);
            },
        201: function (data, textStatus, jqXHR) {
                 log(data);
            },
        400: function(data, textStatus, jqXHR) {
                log(data);
            },
    },
});

the 400 is used when the validation in backend (Pyramid) fails. Now from Pyramid how do I return HTTPBadRequest() response together with a json data that contains the errors of validation? I tried something like:

response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response

But when I inspect in firebug it returns 400 (Bad Request) which is good but it never parses the json response from data.responseText above.

3 Answers

I found a simple way to do it more generic then the accepted answer, I got it with this code

I include exception_response in my view

from pyramid.httpexceptions import exception_response

I raise the 400 exception where I need to

 raise exception_response(400)

In my exceptions script, I trap all exceptions to return generic json and I trap 400 to return a specific json

from pyramid.view import exception_view_config

from pyramid.httpexceptions import (
    HTTPException,
    HTTPBadRequest
)


@exception_view_config(HTTPException, renderer='json')
def exc_view_exception(message, request):
    return {'error': str(message)}


@exception_view_config(HTTPBadRequest, renderer='json')
# Exception 400 bad request
def exc_view_bad_request(message, request):
    body = {
        "message": str(message),
        "status": 400
    }
    request.response.status = 400
    return body
Related