pythonbackendforemanquart

Got must be real number, not BadRequest error when I am trying to return http error


I am building a python api using quart, and using foreman to run it. When I am trying to return some error code, it does not run correctly but returns a html and tells me it needs to be real number, not bad request. My code looks like this for getting all info of a game from DB

@app.route("/games/info/<int:game_id>", methods=["GET"])
async def display_game_info(game_id):
    db = await _get_db()
    try:
        data = await db.fetch_all(
            "SELECT * FROM GameStats where game_id = :game_id;",
            values={"game_id": game_id},
        )
    except sqlite3.IntegrityError as e:
        abort(409,e)
    if data == []:
        abort(400,{"error":"game not exist!"})
#.........
# modify format and return
# ……

If I enter a game ID that exists, it would return the correct result, but if I try to enter a game_id that does not exist, it would return a long HTML that contains the error message. In this case, within the long HTML returned, I can find

<h1>TypeError <span>must be real number, not BadRequest</span></h1>

My 400 error handler is like this

@app.errorhandler(400)
def bad_request(e):
    return {"error": str(e)}, 400

I have tried to see which line gets the error, and everything works fine before

abort(400,{"error":"game not exist!"})

How can I fix this error?

Just figured it out. Changing

return {"error": str(e)}, 400

to

return {"error": e.description}, 400

can solve the issue. Seems this error happens because str has some issue with converting werkzeug.exceptions class object to string.


Solution

  • I figured it out. Changing

    return {"error": str(e)}, 400
    

    to

    return {"error": e.description}, 400
    

    can solve the issue. Seems this error happens because str has some issue with converting werkzeug.exceptions class object to string.