简体   繁体   中英

Return an HTTP fail (e.g. 500) response with JSON body from flask?

As of flask 1.1.x, it is easy to return a JSON response body along with an HTTP success code, such as

return {"success": 1, "message": "You did it!"}, 200

However, returning an HTTP failure status the same way

return {"success": 0, "message": "You screwed up."}, 400

only seems to return a response header and message, (eg HTTP/1.0 INVALID REQUEST )

The Content-type header (correctly) says application/json , but, the body is empty. This happens for any non-2xx class status code.

Flask documentation implies I should be able to do this, but, nothing I've tried seems to work. This includes creating specialized error handlers like

@app.errorhandler(400)
def custom400(error):
    return jsonify({'message': error})

and then calling abort(400, 'my error message') , which doesn't work since the error argument to the handler isn't the string passed to abort , but, is always an error object of whatever type the HTTP error is (eg 410 -> <GONE Gone> .

Is this "normal" HTTP response behaviour, or is flask doing something weird?

It turns out this is more PEBKAC than anything else. I had set a breakpoint inside my $.ajax.error handler, looking at the returned response in the browser (chrome) debug window when the breakpoint fired.

But,the body of the response isn't made available to the debug window until AFTER this handler exists. Once I continued execution of the error handler, the JSON response body is came through as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM