This exists to encapsulate a number of common patterns when returning errors from Axum routes. These patterns include:
- wanting to return error responses as a JSON object
- to automatically convert errors raised in the route hander into that standardised JSON response
- provide appropriate default error messages for public use, which takes into account the status code in use
- a need to optionally add extra data to the error JSON output
A basic tutorial
Below is a mock example route to download a User object:
use State;
use RouteError;
use DatabaseConnection;
pub async
If the get_user_from_database
function returns an error,
then the handler will return a Response.
The Response will have a 500 status code (for an internal error),
and return the following output:
Different RouteError
types
Let's presume get_user_from_database
returns a Result<Option, Error>
.
We want to return a 500 if it returns an error (like above),
and change the code to return a 404 if the user is not found.
use State;
use RouteError;
use DatabaseConnection;
pub async
If the user is not found (get_user_from_database
returns None
),
then this will return a 404 Response with the following JSON:
Adding additional error data
Next let's add extra information to the error. Something more than just an error message.
This can be done by making a new type that serializes using Serde,
and then adding this to the RouteError
.
use State;
use RouteError;
use DatabaseConnection;
use Deserialize;
use Serialize;
// The additional error information needs to derive these three traits.
pub async
If the user is not found (get_user_from_database
returns None
),
then this will return a 404 Response with the following JSON:
Making Internal Errors public
Sometimes you want to make internal errors public, such as for internal services.
For this you can use the RouteInternalError
. It's identical,
but adds adds internal_error
information to the response.