From c745b9db96045d17fb1eeddf7282c96b2d8080a6 Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Tue, 12 Jul 2022 21:59:11 +0200 Subject: [PATCH] chore: update errors types --- core/src/logger.rs | 4 +--- database/src/lib.rs | 3 --- database/src/sqlite.rs | 45 +++++++++++++++++++++++------------- server/src/auth/login.rs | 4 ++-- server/src/auth/register.rs | 4 ++-- server/src/middleware/jwt.rs | 2 +- types/src/errors/auth.rs | 10 +------- types/src/errors/database.rs | 27 +++++++--------------- types/src/errors/fs.rs | 25 ++++++-------------- types/src/errors/server.rs | 33 ++++++-------------------- 10 files changed, 58 insertions(+), 99 deletions(-) diff --git a/core/src/logger.rs b/core/src/logger.rs index 9292b74..452e718 100644 --- a/core/src/logger.rs +++ b/core/src/logger.rs @@ -13,7 +13,5 @@ pub fn init() { better_panic::install(); // initialize tracing - tracing_subscriber::fmt() - .with_max_level(MAX_LEVEL) - .init(); + tracing_subscriber::fmt().with_max_level(MAX_LEVEL).init(); } diff --git a/database/src/lib.rs b/database/src/lib.rs index a40f543..104bcc6 100644 --- a/database/src/lib.rs +++ b/database/src/lib.rs @@ -2,10 +2,7 @@ mod sqlite; -/// Imported from [homedisk_types::database::User]. pub use homedisk_types::database::User; -/// Imported from [homedisk_types::errors::DatabaseError]. pub use homedisk_types::errors::DatabaseError as Error; -/// Imported from [homedisk_types::errors::DatabaseResult]. pub use homedisk_types::errors::DatabaseResult as Result; pub use sqlite::*; diff --git a/database/src/sqlite.rs b/database/src/sqlite.rs index b0c95f2..ea974ab 100644 --- a/database/src/sqlite.rs +++ b/database/src/sqlite.rs @@ -1,8 +1,11 @@ use std::str::FromStr; use futures_util::TryStreamExt; -use sqlx::{sqlite::{SqliteQueryResult, SqliteConnectOptions}, Executor, Row, SqlitePool, ConnectOptions}; -use tracing::{log::LevelFilter, debug}; +use sqlx::{ + sqlite::{SqliteConnectOptions, SqliteQueryResult}, + ConnectOptions, Executor, Row, SqlitePool, +}; +use tracing::{debug, log::LevelFilter}; use super::{Error, Result, User}; @@ -31,13 +34,15 @@ impl Database { debug!("Opening SQLite database"); // sqlite connection options - let mut options = SqliteConnectOptions::from_str(path)?; + let mut options = SqliteConnectOptions::from_str(path).map_err(Error::OpenDatabase)?; // set log level to Debug options.log_statements(LevelFilter::Debug); // create a database pool - let conn = SqlitePool::connect_with(options.clone()).await?; + let conn = SqlitePool::connect_with(options.clone()) + .await + .map_err(Error::ConnectDatabase)?; // return `Database` Ok(Self { conn }) @@ -54,7 +59,7 @@ impl Database { pub async fn create_tables(&self) -> Result { let query = sqlx::query(include_str!("../../tables.sql")); - Ok(self.conn.execute(query).await?) + self.conn.execute(query).await.map_err(Error::Execute) } /// Create a new User @@ -82,7 +87,7 @@ impl Database { .bind(&user.password); // execute query and return output - Ok(self.conn.execute(query).await?) + self.conn.execute(query).await.map_err(Error::Execute) } /// Search for a user @@ -113,14 +118,18 @@ impl Database { let mut stream = self.conn.fetch(query); // get rows from query - let row = stream.try_next().await?.ok_or(Error::UserNotFound)?; + let row = stream + .try_next() + .await + .map_err(Error::Execute)? + .ok_or(Error::UserNotFound)?; // get `id` row - let id = row.try_get("id")?; + let id = row.try_get("id").map_err(Error::GetRow)?; // get `username` row - let username = row.try_get("username")?; + let username = row.try_get("username").map_err(Error::GetRow)?; // get `password` row - let password = row.try_get("password")?; + let password = row.try_get("password").map_err(Error::GetRow)?; // return `User` Ok(User { @@ -155,14 +164,18 @@ impl Database { let mut stream = self.conn.fetch(query); // get rows from query - let row = stream.try_next().await?.ok_or(Error::UserNotFound)?; + let row = stream + .try_next() + .await + .map_err(Error::Execute)? + .ok_or(Error::UserNotFound)?; // get `id` row - let id = row.try_get("id")?; + let id = row.try_get("id").map_err(Error::GetRow)?; // get `username` row - let username = row.try_get("username")?; + let username = row.try_get("username").map_err(Error::GetRow)?; // get `password` row - let password = row.try_get("password")?; + let password = row.try_get("password").map_err(Error::GetRow)?; // return `User` Ok(User { @@ -243,7 +256,7 @@ mod tests { assert_eq!(err.to_string(), "user not found") } - /// Test a search for a user who does not exist + /// Test a search for a user who doesn't exist #[tokio::test] async fn find_user_wrong_username() { let db = open_db().await; @@ -257,7 +270,7 @@ mod tests { assert_eq!(err.to_string(), "user not found") } - /// Test a search for a user by UUID who does not exist + /// Test a search for a user by UUID who doesn't exist #[tokio::test] async fn find_user_wrong_id() { let db = open_db().await; diff --git a/server/src/auth/login.rs b/server/src/auth/login.rs index f65e86a..472dff7 100644 --- a/server/src/auth/login.rs +++ b/server/src/auth/login.rs @@ -29,7 +29,7 @@ pub async fn handle( Response::LoggedIn { access_token: token, } - } + }, // error while searching for a user Err(err) => { @@ -39,7 +39,7 @@ pub async fn handle( // other error _ => Err(ServerError::AuthError(AuthError::Other(err.to_string()))), }; - } + }, }; Ok(Json(response)) diff --git a/server/src/auth/register.rs b/server/src/auth/register.rs index 022fb5d..17336cf 100644 --- a/server/src/auth/register.rs +++ b/server/src/auth/register.rs @@ -42,7 +42,7 @@ pub async fn handle( Response::LoggedIn { access_token: token, } - } + }, // error while searching for a user Err(err) => { @@ -53,7 +53,7 @@ pub async fn handle( // other error return Err(ServerError::AuthError(AuthError::Other(err.to_string()))); - } + }, }; // create directory for user files diff --git a/server/src/middleware/jwt.rs b/server/src/middleware/jwt.rs index a8fc846..1bac704 100644 --- a/server/src/middleware/jwt.rs +++ b/server/src/middleware/jwt.rs @@ -20,7 +20,7 @@ pub async fn find_user(db: &Database, user_id: &str) -> Result { Err(ServerError::AuthError(AuthError::UserNotFound)) - } + }, // other error _ => Err(ServerError::AuthError(AuthError::Other(err.to_string()))), }, diff --git a/types/src/errors/auth.rs b/types/src/errors/auth.rs index f417b40..66b9ad0 100644 --- a/types/src/errors/auth.rs +++ b/types/src/errors/auth.rs @@ -3,28 +3,20 @@ use thiserror::Error; #[derive(Debug, Clone, Serialize, Deserialize, Error)] pub enum Error { - /// Username or Password incorrect. #[error("user not found")] UserNotFound, - /// Cannot create a user because username already exists. #[error("user already exists")] UserAlreadyExists, - /// Username is too short. #[error("username is too short")] UsernameTooShort, - /// Username is too long. #[error("username is too long")] UsernameTooLong, - /// Password is too short. #[error("password is too short")] PasswordTooShort, - /// Failed to generate user token. - #[error("generate jwt token")] + #[error("failed to generate jwt token")] TokenGenerate, - /// Incorrect user token. #[error("invalid jwt token")] InvalidToken, - /// Other error. #[error("other error - {0}")] Other(String), } diff --git a/types/src/errors/database.rs b/types/src/errors/database.rs index eda3efa..ff7f3fb 100644 --- a/types/src/errors/database.rs +++ b/types/src/errors/database.rs @@ -3,27 +3,16 @@ use thiserror::Error; /// Database Error #[derive(Debug, Error)] pub enum Error { - /// Username or Password incorrect. #[error("user not found")] UserNotFound, - /// [sqlx::Error](https://docs.rs/sqlx/latest/sqlx/enum.Error.html) - #[error("sqlx error - {0}")] - SQLx(sqlx::Error), - /// [std::io::Error] - #[error("std::io error - {0}")] - StdIo(std::io::Error), -} - -impl From for Error { - fn from(err: sqlx::Error) -> Self { - Error::SQLx(err) - } -} - -impl From for Error { - fn from(err: std::io::Error) -> Self { - Error::StdIo(err) - } + #[error("failed to open database: {0}")] + OpenDatabase(sqlx::Error), + #[error("failed to connect to the database: {0}")] + ConnectDatabase(sqlx::Error), + #[error("failed to get row: {0}")] + GetRow(sqlx::Error), + #[error("failed to execute the query: {0}")] + Execute(sqlx::Error), } /// Custom Result alias for a [enum@Error]. diff --git a/types/src/errors/fs.rs b/types/src/errors/fs.rs index af7173d..1dafa04 100644 --- a/types/src/errors/fs.rs +++ b/types/src/errors/fs.rs @@ -3,37 +3,26 @@ use thiserror::Error; #[derive(Debug, Clone, Serialize, Deserialize, Error)] pub enum Error { - /// File doesn't exists. #[error("file doesn't exists")] FileDoesNotExist, - /// File already exists. #[error("file already exists")] FileAlreadyExists, - /// Error when parsing multipart. #[error("unexpected multipart error")] MultipartError, - /// Failed to create a file. - #[error("create file - {0}")] + #[error("failed to create create a file - {0}")] CreateFile(String), - /// Failed to create a directory. - #[error("create dir - {0}")] + #[error("failed to create a directory - {0}")] CreateDirectory(String), - /// Failed to delete file. - #[error("delete file - {0}")] + #[error("failed to delete file: {0}")] DeleteFile(String), - /// Failed to delete directory. - #[error("delete dir - {0}")] + #[error("failed to delete directory: {0}")] DeleteDirectory(String), - /// Failed to write content to file. - #[error("write file - {0}")] + #[error("failed to write content to file: {0}")] WriteFile(String), - /// Failed decoding base64. - #[error("base64 - {0}")] + #[error("failed to decode base64: {0}")] Base64(String), - /// Error when paths in directory. - #[error("read dir - {0}")] + #[error("failed to read directory: {0}")] ReadDirectory(String), - /// Other error. #[error("other error - {0}")] Other(String), } diff --git a/types/src/errors/server.rs b/types/src/errors/server.rs index 4ca98ef..f442a7e 100644 --- a/types/src/errors/server.rs +++ b/types/src/errors/server.rs @@ -7,29 +7,21 @@ use super::{AuthError, FsError}; #[derive(Debug, Clone, Serialize, Deserialize, Error)] #[serde(tag = "error", content = "error_message", rename_all = "kebab-case")] pub enum Error { - /// Auth error. #[error("auth error - {0}")] AuthError(#[from] AuthError), - /// File System Error. #[error("fs error - {0}")] FsError(#[from] FsError), - /// User sends too many requests. #[error("too may requests, please slow down")] TooManyRequests, - /// Missing Json in Content-Type Header. - #[error("missing json content type")] + #[error("missing json in Content-Type header")] MissingJsonContentType, - /// Failed to deserialize JSON. - #[error("error deserialize json")] + #[error("failed to deserialize json")] JsonDataError, - /// Syntax error in JSON. - #[error("json syntax error")] + #[error("syntax error in json")] JsonSyntaxError, - /// Failed to extract the Request body. #[error("failed to extract the request body")] BytesRejection, - /// Other error. - #[error("unknown error - {0}")] + #[error("other error - {0}")] Other(String), } @@ -40,34 +32,23 @@ impl axum::response::IntoResponse for Error { let status = match self { Self::AuthError(ref err) => match err { - AuthError::UserNotFound => StatusCode::BAD_REQUEST, - AuthError::UserAlreadyExists => StatusCode::BAD_REQUEST, - AuthError::UsernameTooShort => StatusCode::BAD_REQUEST, - AuthError::UsernameTooLong => StatusCode::BAD_REQUEST, - AuthError::PasswordTooShort => StatusCode::BAD_REQUEST, AuthError::TokenGenerate => StatusCode::INTERNAL_SERVER_ERROR, - AuthError::InvalidToken => StatusCode::BAD_REQUEST, AuthError::Other(_) => StatusCode::INTERNAL_SERVER_ERROR, + _ => StatusCode::BAD_REQUEST, }, Self::FsError(ref err) => match err { - FsError::FileAlreadyExists => StatusCode::BAD_REQUEST, - FsError::FileDoesNotExist => StatusCode::BAD_REQUEST, - FsError::MultipartError => StatusCode::BAD_REQUEST, 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, - FsError::Base64(_) => StatusCode::BAD_REQUEST, - FsError::ReadDirectory(_) => StatusCode::BAD_REQUEST, FsError::Other(_) => StatusCode::INTERNAL_SERVER_ERROR, + _ => StatusCode::BAD_REQUEST, }, Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS, - Self::MissingJsonContentType => StatusCode::BAD_REQUEST, - Self::JsonDataError => StatusCode::BAD_REQUEST, - Self::JsonSyntaxError => StatusCode::BAD_REQUEST, Self::BytesRejection => StatusCode::INTERNAL_SERVER_ERROR, Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR, + _ => StatusCode::BAD_REQUEST, }; let mut response = axum::Json(self).into_response();