-2

I'm trying to handle errors in Flask:

def handle_error(error):
    if error.status_code == 404:
        return make_response(jsonify({ "error": { "code": 404, "message": "Not found" } }), 404)
    else:
        return make_response(jsonify({ "error": { "code": 500, "message": "Internal server error" } }), 500)

If the endpoint is not found, it should return a JSON with 404 code. In any other case, it is to return JSON with code 500. I open an endpoint that doesn't exist and get error 500 from Flask:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

What am I doing wrong?

napster993
  • 165
  • 3
  • 10

1 Answers1

1

You can use annotation for error handling:

@app.errorhandler(404)
def errorhandler(e)
    return xyz

You can find documentation here https://flask.palletsprojects.com/en/1.1.x/errorhandling/

also https://www.codementor.io/@lakshyasri/custom-error-pages-in-flask-xrgye5l5e