I want to catch all errors and return an error in json format for my api project.
This is my error handler:
@app.errorhandler(Exception)
def handle_exception(e):
if not isinstance(e, HTTPException):
print(e)
return {
"code": 500,
"name": "Internal Server Error",
"description": repr(e),
}, 500
else:
response = e.get_response()
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response
My errorhandler is catching exceptions if it happens inside the view function:
@api.get("/")
def all(user):
a.b
return []
This successfully catchs the following exception and return a json response:
name 'a' is not defined
But it is not catching if view function is fine but the return value is not json-friendly:
@api.get("/")
def all(user):
return 1
It raises the folloing error and returns an error in html format.
TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a int.