Implement basic error handling with anyhow
This commit is contained in:
26
src/error.rs
Normal file
26
src/error.rs
Normal file
@ -0,0 +1,26 @@
|
||||
use axum::{response::{IntoResponse, Response}, http::StatusCode};
|
||||
|
||||
pub struct AppError(anyhow::Error);
|
||||
|
||||
// Tell axum how to convert `AppError` into a response.
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let status_code = match self.0.downcast_ref::<StatusCode>() {
|
||||
Some(status_code) => *status_code,
|
||||
None => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
tracing::error!("{:#}", self.0);
|
||||
status_code.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())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user