Module error_handling
Error handling model and utilities
axum's error handling model
axum is based on tower::Service which bundles errors through its associated
Error type. If you have a Service that produces an error and that error
makes it all the way up to hyper, the connection will be terminated without
sending a response. This is generally not desirable so axum makes sure you
always produce a response by relying on the type system.
axum does this by requiring all services have Infallible as their error
type. Infallible is the error type for errors that can never happen.
This means if you define a handler like:
use StatusCode;
async
While it looks like it might fail with a StatusCode this actually isn't an
"error". If this handler returns Err(some_status_code) that will still be
converted into a Response and sent back to the client. This is done
through StatusCode's IntoResponse implementation.
It doesn't matter whether you return Err(StatusCode::NOT_FOUND) or
Err(StatusCode::INTERNAL_SERVER_ERROR). These are not considered errors in
axum.
Instead of a direct StatusCode, it makes sense to use intermediate error type
that can ultimately be converted to Response. This allows using ? operator
in handlers. See those examples:
anyhow-error-responsefor generic boxed errorserror-handlingfor application-specific detailed errors
This also applies to extractors. If an extractor doesn't match the request the
request will be rejected and a response will be returned without calling your
handler. See extract to learn more about handling extractor
failures.
Routing to fallible services
You generally don't have to think about errors if you're only using async
functions as handlers. However if you're embedding general Services or
applying middleware, which might produce errors you have to tell axum how to
convert those errors into responses.
use ;
async
// this service might fail with `anyhow::Error`
let some_fallible_service = service_fn;
let app = new.route_service;
// handle errors by converting them into something that implements
// `IntoResponse`
async
# let _: Router = app;
Applying fallible middleware
Similarly axum requires you to handle errors from middleware. That is done with
[HandleErrorLayer]:
use ;
use Duration;
use ServiceBuilder;
let app = new
.route
.layer;
async
# let _: Router = app;
Running extractors for error handling
HandleErrorLayer also supports running extractors:
use ;
use Duration;
use ServiceBuilder;
let app = new
.route
.layer;
async
# let _: Router = app;
Modules
- future Future types.
Structs
-
HandleError
A
Serviceadapter that handles errors by converting them into responses. -
HandleErrorLayer
Layerthat appliesHandleErrorwhich is aServiceadapter that handles errors by converting them into responses.