1
0
Fork 0
forked from 2sys/shoutdotdev
shoutdotdev/src/app_error.rs

39 lines
1.2 KiB
Rust
Raw Normal View History

2025-02-26 13:10:50 -08:00
use anyhow::Error;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
// Use anyhow, define error and enable '?'
// For a simplified example of using anyhow in axum check /examples/anyhow-error-response
#[derive(Debug)]
pub enum AppError {
InternalServerError(Error),
ForbiddenError(String),
2025-02-26 13:10:50 -08:00
}
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
Self::InternalServerError(err) => {
2025-02-26 13:10:47 -08:00
tracing::error!("Application error: {:?}", err);
2025-02-26 13:10:50 -08:00
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
}
Self::ForbiddenError(client_message) => {
tracing::info!("Forbidden: {}", client_message);
(StatusCode::FORBIDDEN, client_message).into_response()
}
2025-02-26 13:10:50 -08:00
}
}
}
// 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::InternalServerError(Into::<anyhow::Error>::into(err))
}
}