-
Notifications
You must be signed in to change notification settings - Fork 968
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example showing how to return
anyhow::Error
s (#1398)
- Loading branch information
1 parent
de9909d
commit 112f535
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
[package] | ||
name = "example-anyhow-error-response" | ||
version = "0.1.0" | ||
edition = "2021" | ||
publish = false | ||
|
||
[dependencies] | ||
anyhow = "1.0" | ||
axum = { path = "../../axum" } | ||
tokio = { version = "1.0", features = ["full"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
//! Run with | ||
//! | ||
//! ```not_rust | ||
//! cd examples && cargo run -p example-anyhow-error-response | ||
//! ``` | ||
|
||
use axum::{ | ||
http::StatusCode, | ||
response::{IntoResponse, Response}, | ||
routing::get, | ||
Router, | ||
}; | ||
use std::net::SocketAddr; | ||
|
||
#[tokio::main] | ||
async fn main() { | ||
let app = Router::new().route("/", get(handler)); | ||
|
||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); | ||
println!("listening on {}", addr); | ||
axum::Server::bind(&addr) | ||
.serve(app.into_make_service()) | ||
.await | ||
.unwrap(); | ||
} | ||
|
||
async fn handler() -> Result<(), AppError> { | ||
try_thing()?; | ||
Ok(()) | ||
} | ||
|
||
fn try_thing() -> Result<(), anyhow::Error> { | ||
anyhow::bail!("it failed!") | ||
} | ||
|
||
// Make our own error that wraps `anyhow::Error`. | ||
struct AppError(anyhow::Error); | ||
|
||
// Tell axum how to convert `AppError` into a response. | ||
impl IntoResponse for AppError { | ||
fn into_response(self) -> Response { | ||
( | ||
StatusCode::INTERNAL_SERVER_ERROR, | ||
format!("Something went wrong: {}", self.0), | ||
) | ||
.into_response() | ||
} | ||
} | ||
|
||
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into | ||
// `Result<_, AppError>`. That way you don't need to do that manually. | ||
impl<E> From<E> for AppError | ||
where | ||
E: Into<anyhow::Error>, | ||
{ | ||
fn from(err: E) -> Self { | ||
Self(err.into()) | ||
} | ||
} |