HomeDisk/types/src/errors/server.rs

72 lines
2.4 KiB
Rust
Raw Normal View History

2022-06-08 19:16:12 +00:00
use serde::{Deserialize, Serialize};
2022-06-23 09:52:48 +00:00
use thiserror::Error;
2022-06-08 19:16:12 +00:00
use super::{AuthError, FsError};
/// HTTP Server Error
2022-06-23 09:52:48 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Error)]
2022-06-08 19:16:12 +00:00
#[serde(tag = "error", content = "error_message", rename_all = "kebab-case")]
pub enum Error {
#[error("auth error: {0}")]
2022-06-08 19:16:12 +00:00
AuthError(#[from] AuthError),
#[error("fs error: {0}")]
2022-06-08 19:16:12 +00:00
FsError(#[from] FsError),
#[error("too may requests, please slow down")]
TooManyRequests,
#[error("invalid Content-Type")]
InvalidContentType,
2022-07-12 19:59:11 +00:00
#[error("failed to deserialize json")]
2022-06-08 19:16:12 +00:00
JsonDataError,
2022-07-12 19:59:11 +00:00
#[error("syntax error in json")]
2022-06-08 19:16:12 +00:00
JsonSyntaxError,
#[error("failed to extract the request body")]
BytesRejection,
#[error("other error: {0}")]
2022-06-08 19:16:12 +00:00
Other(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum ResponseError {
Error(String),
}
impl Error {
fn into_response(self) -> ResponseError {
ResponseError::Error(self.to_string())
}
}
2022-06-08 19:16:12 +00:00
#[cfg(feature = "axum")]
impl axum::response::IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
let status = match self {
Self::AuthError(ref err) => match err {
AuthError::TokenGenerate => StatusCode::INTERNAL_SERVER_ERROR,
2022-06-11 08:19:47 +00:00
AuthError::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
2022-07-12 19:59:11 +00:00
_ => StatusCode::BAD_REQUEST,
2022-06-08 19:16:12 +00:00
},
Self::FsError(ref err) => match err {
FsError::CreateFile(_) => StatusCode::INTERNAL_SERVER_ERROR,
FsError::CreateDirectory(_) => StatusCode::INTERNAL_SERVER_ERROR,
FsError::DeleteFile(_) => StatusCode::INTERNAL_SERVER_ERROR,
FsError::DeleteDirectory(_) => StatusCode::INTERNAL_SERVER_ERROR,
FsError::WriteFile(_) => StatusCode::INTERNAL_SERVER_ERROR,
2022-06-11 08:19:47 +00:00
FsError::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
2022-07-12 19:59:11 +00:00
_ => StatusCode::BAD_REQUEST,
2022-06-08 19:16:12 +00:00
},
Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
Self::BytesRejection => StatusCode::INTERNAL_SERVER_ERROR,
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
2022-07-12 19:59:11 +00:00
_ => StatusCode::BAD_REQUEST,
2022-06-08 19:16:12 +00:00
};
let mut response = axum::Json(self.into_response()).into_response();
2022-06-08 19:16:12 +00:00
*response.status_mut() = status;
response
}
}