简体   繁体   中英

How to return a json response from a flask error handler?

I have a Flask app where I register an error as:

app.register_error_handler(401, handle_errors)

and my handle_errors function looks like this:

def handle_errors(error):
    response = make_response()
    response.data = str(error.to_dict())
    response.content_type = "application/json"
    response.status_code = 401
    return response, response.status_code

However, when I invoke my API my response looks like this:

< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: text/html; charset=utf-8
...

Why does it return it as text/html even though I set the content_type to application/json ?

import json

from flask import Flask, Response, abort

app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True

#register 500 error handler
@app.errorhandler(Exception)
# handle all other exception
def all_exception_handler(error):
    res = {"error": str(error)}
    return Response(status=500, mimetype="application/json", response=json.dumps(res))


# handle 401 exception
def error_401_handler(error):
    res = {"error": "Unauthorized"}
    return Response(status=401, mimetype="application/json", response=json.dumps(res))


# test exception 500 with http get
@app.route("/test500")
def test500():
    raise Exception("test exception")


# test exception 401 with http get
@app.route("/test401")
def test401():
    abort(401)


# register 401 error handler
app.register_error_handler(401, error_401_handler)

app.run(host="0.0.0.0")


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