Custom Error Pages
Depending on the error code it is less or more likely for the user toactually see such an error.
The following error codes are some that are often displayed to the user,even if the application behaves correctly:
The good old “chap, you made a mistake typing that URL” message. Socommon that even novices to the internet know that 404 means: damn,the thing I was looking for is not there. It’s a very good idea tomake sure there is actually something useful on a 404 page, at least alink back to the index.
403 Forbidden
Did you know that there the “404 Not Found” has a brother named “410Gone”? Few people actually implement that, but the idea is thatresources that previously existed and got deleted answer with 410instead of 404. If you are not deleting documents permanently fromthe database but just mark them as deleted, do the user a favour anduse the 410 code instead and display a message that what they werelooking for was deleted for all eternity.
500 Internal Server Error
- Usually happens on programming errors or if the server is overloaded.A terribly good idea is to have a nice page there, because yourapplication will fail sooner or later (see also:Application Errors).
An error handler is a function that returns a response when a type of error israised, similar to how a view is a function that returns a response when arequest URL is matched. It is passed the instance of the error being handled,which is most likely a . An errorhandler for “500 Internal Server Error” will be passed uncaught exceptions inaddition to explicit 500 errors.
The status code of the response will not be set to the handler’s code. Makesure to provide the appropriate HTTP status code when returning a response froma handler.
A handler for “500 Internal Server Error” will not be used when running indebug mode. Instead, the interactive debugger will be shown.
Here is an example implementation for a “404 Page Not Found” exception:
When using the application factory pattern:
When using Flask for web APIs, you can use the same techniques as aboveto return JSON responses to API errors. is calledwith a description
parameter. The willuse that as the JSON error message, and set the status code to 404.