Flask provides support for error handling, including defining custom errors. When an error occurs which is not otherwise defined, the default error code is 500 (internal server error).
In this post I will show a minimal example of using a predefined code for error handling in a Flask application.
"""Flask application demonstrating basic error handling."""
from flask import Flask
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(error):
return "This page does not exist (DONE)", 404
def main() -> None:
app.run(debug=True)
if __name__ == "__main__":
main()In the above code we picked the classic 404 error, which is reserved for when the page cannot be reached. XKCD has an appropriate entry on this topic.