From ab23761e090b8ab6311a360eada7131f6663a3bf Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 1 Sep 2022 18:45:04 +0200 Subject: Fork from m6-ie project --- src/errors.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/errors.rs (limited to 'src/errors.rs') diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..e541eda --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,63 @@ +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, + Json, +}; +use serde_json::json; + +/// All errors raised by the web app +pub enum AppError { + /// Generic error, never called yet + Generic, + /// Database error + Database, + /// Generic bad request. It is handled with a message value + BadRequest(String), + /// Not found error + NotFound, + /// Raised when a token is not good created + TokenCreation, + /// Raised when a passed token is not valid + InvalidToken, +} + +/// Use `AppError` as response for an endpoint +impl IntoResponse for AppError { + /// Matches `AppError` into a tuple of status and error message. + /// The response will be a JSON in the format of: + /// ```json + /// { "error": "" } + /// ``` + fn into_response(self) -> Response { + let (status, error_message) = match self { + AppError::Generic => ( + StatusCode::INTERNAL_SERVER_ERROR, + "Generic error, can't find why".to_string(), + ), + AppError::Database => ( + StatusCode::INTERNAL_SERVER_ERROR, + "Error with database connection".to_string(), + ), + AppError::BadRequest(value) => (StatusCode::BAD_REQUEST, value), + AppError::NotFound => (StatusCode::NOT_FOUND, "Element not found".to_string()), + AppError::TokenCreation => ( + StatusCode::INTERNAL_SERVER_ERROR, + "Token creation error".to_string(), + ), + AppError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token".to_string()), + }; + + let body = Json(json!({ + "error": error_message, + })); + + (status, body).into_response() + } +} + +/// Transforms a `sqlx::Error` into a `AppError::Databse` error +impl From for AppError { + fn from(_error: sqlx::Error) -> AppError { + AppError::Database + } +} -- cgit v1.2.3-71-g8e6c