rieter/server/src/error.rs

96 lines
2.6 KiB
Rust
Raw Normal View History

2024-05-27 22:56:37 +02:00
use std::{error::Error, fmt, io};
2024-05-27 22:56:37 +02:00
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub type Result<T> = std::result::Result<T, ServerError>;
#[derive(Debug)]
pub enum ServerError {
IO(io::Error),
Axum(axum::Error),
Db(sea_orm::DbErr),
2023-07-31 23:11:02 +02:00
Status(StatusCode),
Archive(libarchive::error::ArchiveError),
2024-06-13 09:21:56 +02:00
Figment(figment::Error),
2024-06-13 18:40:24 +02:00
Unit,
}
impl fmt::Display for ServerError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServerError::IO(err) => write!(fmt, "{}", err),
ServerError::Axum(err) => write!(fmt, "{}", err),
ServerError::Status(status) => write!(fmt, "{}", status),
ServerError::Db(err) => write!(fmt, "{}", err),
ServerError::Archive(err) => write!(fmt, "{}", err),
2024-06-13 09:21:56 +02:00
ServerError::Figment(err) => write!(fmt, "{}", err),
2024-06-13 18:40:24 +02:00
ServerError::Unit => Ok(()),
}
}
}
impl Error for ServerError {}
impl IntoResponse for ServerError {
fn into_response(self) -> Response {
tracing::error!("{:?}", self);
match self {
ServerError::IO(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
ServerError::Axum(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
ServerError::Status(status) => status.into_response(),
2023-07-30 18:21:07 +02:00
ServerError::Db(sea_orm::DbErr::RecordNotFound(_)) => {
StatusCode::NOT_FOUND.into_response()
}
2024-06-13 18:40:24 +02:00
ServerError::Db(_) | ServerError::Archive(_) | ServerError::Figment(_) | ServerError::Unit => {
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
}
}
}
impl From<io::Error> for ServerError {
fn from(err: io::Error) -> Self {
ServerError::IO(err)
}
}
impl From<axum::Error> for ServerError {
fn from(err: axum::Error) -> Self {
ServerError::Axum(err)
}
}
impl From<tokio::task::JoinError> for ServerError {
fn from(err: tokio::task::JoinError) -> Self {
ServerError::IO(err.into())
}
}
impl From<StatusCode> for ServerError {
fn from(status: StatusCode) -> Self {
Self::Status(status)
}
}
impl From<sea_orm::DbErr> for ServerError {
fn from(err: sea_orm::DbErr) -> Self {
ServerError::Db(err)
}
}
impl From<libarchive::error::ArchiveError> for ServerError {
fn from(err: libarchive::error::ArchiveError) -> Self {
ServerError::Archive(err)
}
}
2024-06-13 09:21:56 +02:00
impl From<figment::Error> for ServerError {
fn from(err: figment::Error) -> Self {
ServerError::Figment(err)
}
}