axum_error/lib.rs
1//! Provides an `Error` type which can be used in a `eyre`-like fashion
2//! for `axum`
3//!
4//! ```rust
5//! use axum::{response::Html, routing::get, Router};
6//! use std::{fs::read_to_string, net::SocketAddr};
7//! use axum_error::Result;
8//!
9//! #[tokio::main]
10//! async fn main() {
11//! let app = Router::new().route("/", get(index));
12//! axum::Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
13//! .serve(app.into_make_service())
14//! .await
15//! .unwrap()
16//! }
17//!
18//! async fn index() -> Result<Html<String>> {
19//! Ok(Html(read_to_string("index.html")?))
20//! }
21//! ```
22
23use axum::{
24 http::StatusCode,
25 response::{IntoResponse, Response},
26};
27
28/// Error type which implements `IntoResponse`
29#[derive(Debug)]
30pub struct Error(pub eyre::Report);
31
32impl<E: Into<eyre::Report>> From<E> for Error {
33 fn from(error: E) -> Self {
34 Error(error.into())
35 }
36}
37
38impl IntoResponse for Error {
39 fn into_response(self) -> Response {
40 (StatusCode::INTERNAL_SERVER_ERROR, format!("{:?}", self.0)).into_response()
41 }
42}
43
44// Result type
45pub type Result<T, E = Error> = std::result::Result<T, E>;