Skip to content

Commit

Permalink
mapped all loco errors
Browse files Browse the repository at this point in the history
  • Loading branch information
DenuxPlays committed Dec 22, 2024
1 parent 4b60715 commit 2e97e9d
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 42 deletions.
1 change: 1 addition & 0 deletions backend/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ impl Hooks for App {
}

async fn truncate(db: &DatabaseConnection) -> Result<()> {
// TODO add all other tables
truncate_table(db, users::Entity).await?;
Ok(())
}
Expand Down
97 changes: 76 additions & 21 deletions backend/src/error/app_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,45 @@ impl JsonReference {
}

// General errors
impl AppError {
#[allow(non_snake_case)]
pub fn GeneralInternalServerError(msg: String) -> Self {
Self {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
error_code: ErrorCode::GENERAL_INTERNAL_SERVER_ERROR,
details: msg,
reference: None,
}
}
}
app_errors!(
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::GENERAL_INTERNAL_SERVER_ERROR, GeneralInternalServerError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::SCHEDULER_ERROR, SchedulerError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::AXUM_ERROR, AxumError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::TERA_ERROR, TeraError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::ENV_VAR_ERROR, EnvVarError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::LETTRE_ERROR, LettreError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::IO_ERROR, IOError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::HASH_ERROR, HashError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::TASK_JOIN_ERROR, TaskJoinError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::REDIS_ERROR, RedisError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::STORAGE_ERROR, StorageError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::CACHE_ERROR, CacheError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::VERSION_CHECK_ERROR, VersionCheckError, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::SMTP_ERROR, SmtpError, argument=String);
);

// Validation errors
app_errors!(
(StatusCode::BAD_REQUEST, ErrorCode::GENERAL_VALIDATION_ERROR, GeneralValidationError, argument=Option<JsonReference>);
(StatusCode::BAD_REQUEST, ErrorCode::INVALID_VERIFICATION_TOKEN, InvalidVerificationToken);
(StatusCode::BAD_REQUEST, ErrorCode::JSON_ERROR, JsonError, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::JSON_REJECTION_ERROR, JsonRejectionError, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::YAML_FILE_ERROR, YamlFileError, argument=YamlFileErrorArgs);
(StatusCode::BAD_REQUEST, ErrorCode::YAML_ERROR, YamlError, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::EMAIL_ADDRESS_PARSING_ERROR, EmailAddressParsingError, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::GENERAL_BAD_REQUEST, GeneralBadRequest, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::INVALID_HEADER_VALUE, InvalidHeaderValue, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::INVALID_HEADER_NAME, InvalidHeaderName, argument=String);
(StatusCode::BAD_REQUEST, ErrorCode::INVALID_HTTP_METHOD, InvalidHttpMethod, argument=String);
);

#[derive(Debug, Clone, Default, Serialize)]
pub struct YamlFileErrorArgs(String, String);

// User errors
app_errors!(
(StatusCode::UNAUTHORIZED, ErrorCode::UNAUTHORIZED, Unauthorized, argument=String);
(StatusCode::NOT_FOUND, ErrorCode::NOT_FOUND, NotFound);
);

// Configuration error
Expand All @@ -74,11 +97,12 @@ app_errors!(
// CLI errors
app_errors!(
(StatusCode::NOT_FOUND, ErrorCode::TASK_NOT_FOUND, TaskNotFound, argument=String);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::GENERATOR_ERROR, GeneratorError, argument=String);
);

// DB Errors
app_errors!(
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::GENERAL_DATABASE_ERROR, GeneralDatabaseError);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::GENERAL_DATABASE_ERROR, GeneralDatabaseError, argument=Option<String>);
(StatusCode::BAD_REQUEST, ErrorCode::ENTITY_ALREADY_EXIST, EntityAlreadyExists);
(StatusCode::NOT_FOUND, ErrorCode::ENTITY_DOES_NOT_EXIST, EntityNotFound);
(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::CONNECTION_ERROR, ConnectionError);
Expand Down Expand Up @@ -108,12 +132,43 @@ impl From<LocoError> for AppError {
LocoError::Message(msg) => AppError::GeneralInternalServerError(msg),
LocoError::QueueProviderMissing => AppError::QueueProviderMissing(),
LocoError::TaskNotFound(msg) => AppError::TaskNotFound(msg),
// TODO: Add missing mappings
e => {
error!("An unmapped loco error occurred: {:?}", e);

AppError::GeneralInternalServerError("An unknown error occurred.".to_string())
}
LocoError::Scheduler(err) => AppError::SchedulerError(err.to_string()),
LocoError::Axum(err) => AppError::AxumError(err.to_string()),
LocoError::Tera(err) => AppError::TeraError(err.to_string()),
LocoError::JSON(err) => AppError::JsonError(err.to_string()),
LocoError::JsonRejection(rej) => AppError::JsonRejectionError(rej.to_string()),
LocoError::YAMLFile(err, path) => AppError::YamlFileError(YamlFileErrorArgs(err.to_string(), path)),
LocoError::YAML(err) => AppError::YamlError(err.to_string()),
LocoError::EnvVar(err) => AppError::EnvVarError(err.to_string()),
LocoError::EmailSender(err) => AppError::LettreError(err.to_string()),
LocoError::Smtp(err) => AppError::SmtpError(err.to_string()),
LocoError::IO(err) => AppError::IOError(err.to_string()),
LocoError::DB(err) => AppError::from(err),
LocoError::ParseAddress(err) => AppError::EmailAddressParsingError(err.to_string()),
LocoError::Hash(reference) => AppError::HashError(reference),
LocoError::Unauthorized(str) => AppError::Unauthorized(str),
LocoError::NotFound => AppError::NotFound(),
LocoError::BadRequest(str) => AppError::GeneralBadRequest(str),
LocoError::CustomError(status, detail) => AppError {
status_code: status,
error_code: ErrorCode::CUSTOM_ERROR,
details: ErrorCode::CUSTOM_ERROR.message.to_string(),
reference: JsonReference::new_with_default_none(&detail),
},
LocoError::InternalServerError => AppError::GeneralInternalServerError(Default::default()),
LocoError::InvalidHeaderValue(err) => AppError::InvalidHeaderValue(err.to_string()),
LocoError::InvalidHeaderName(err) => AppError::InvalidHeaderName(err.to_string()),
LocoError::InvalidMethod(err) => AppError::InvalidHttpMethod(err.to_string()),
LocoError::TaskJoinError(err) => AppError::TaskJoinError(err.to_string()),
LocoError::Model(err) => AppError::from(err),
LocoError::RedisPool(err) => AppError::RedisError(err.to_string()),
LocoError::Redis(err) => AppError::RedisError(err.to_string()),
LocoError::Sqlx(err) => AppError::GeneralDatabaseError(Some(err.to_string())),
LocoError::Storage(err) => AppError::StorageError(err.to_string()),
LocoError::Cache(err) => AppError::CacheError(err.to_string()),
LocoError::Generators(err) => AppError::GeneratorError(err.to_string()),
LocoError::VersionCheck(err) => AppError::VersionCheckError(err.to_string()),
LocoError::Any(err) => AppError::GeneralInternalServerError(err.to_string()),
}
}
}
Expand Down Expand Up @@ -149,7 +204,7 @@ impl From<DbErr> for AppError {
from, into, source
);

AppError::GeneralDatabaseError()
AppError::GeneralDatabaseError(None)
}
DbErr::Conn(err) => {
error!("An error occurred while connecting to the database. Error: {:?}", err);
Expand All @@ -174,10 +229,10 @@ impl From<DbErr> for AppError {
err
);

AppError::GeneralDatabaseError()
AppError::GeneralDatabaseError(None)
}
DbErr::UnpackInsertId => AppError::CouldNotRetrieveLastInsertId(),
DbErr::UpdateGetPrimaryKey => AppError::GeneralDatabaseError(),
DbErr::UpdateGetPrimaryKey => AppError::GeneralDatabaseError(None),
DbErr::RecordNotFound(err) => AppError::RecordNotFound(JsonReference::new_with_default_none(&err)),
DbErr::AttrNotSet(attr) => {
error!("An attribute was not set. Attribute: {}", attr);
Expand Down
76 changes: 55 additions & 21 deletions backend/src/error/error_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use utoipa::ToSchema;

#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash, Serialize, ToSchema)]
pub struct ErrorCode {
pub code: u16,
pub code: u32,
pub message: &'static str,
}

Expand All @@ -27,45 +27,79 @@ macro_rules! error_codes {
// Internal server errors
error_codes!(
(1000, GENERAL_INTERNAL_SERVER_ERROR, "A general internal server error occurred.");
(1001, SCHEDULER_ERROR, "A general error with the scheduler occurred.");
(1002, AXUM_ERROR, "A general error with axum occurred.");
(1003, TERA_ERROR, "A general error occurred while rendering a template");
(1004, ENV_VAR_ERROR, "Unable to parse or load env var.");
(1005, LETTRE_ERROR, "A general error occurred while sending an email.");
(1006, IO_ERROR, "An io error occurred.");
(1007, HASH_ERROR, "An error occurred while hashing a string.");
(1008, TASK_JOIN_ERROR, "An error that occurred when not handling threads correctly.");
(1009, REDIS_ERROR, "A general redis error occurred.");
(1009, STORAGE_ERROR, "A general storage error occurred.");
(1010, CACHE_ERROR, "A general cache error occurred.");
(1011, VERSION_CHECK_ERROR, "Could not complete version check");
(1012, SMTP_ERROR, "A general smtp error occurred.");
);

// Validation errors
// Validation/User errors
error_codes!(
(2000, GENERAL_VALIDATION_ERROR, "A general validation error occurred.");
(2001, INVALID_VERIFICATION_TOKEN, "Invalid verification token.");
(2002, JSON_REJECTION_ERROR, "A json input was rejected.");
(2003, JSON_ERROR, "A general json serialization error occurred.");
(2004, YAML_FILE_ERROR, "Could not parse yaml file.");
(2005, YAML_ERROR, "A general yaml serialization error occurred.");
(2006, EMAIL_ADDRESS_PARSING_ERROR, "Could not parse E-Mail address.");
(2007, GENERAL_BAD_REQUEST, "A general error for bad requests.");
(2008, INVALID_HEADER_VALUE, "A invalid header value was given.");
(2009, INVALID_HEADER_NAME, "A invalid header name was given");
(2010, INVALID_HTTP_METHOD, "A invalid http method was used.");
);

// User errors
error_codes!(
(3001, UNAUTHORIZED, "You are not authorized for this.");
(3002, NOT_FOUND, "Requested resource could not be found.");
);

// Configuration error
error_codes!(
(3001, QUEUE_PROVIDER_MISSING, "No provider is configured for the queue.");
(4001, QUEUE_PROVIDER_MISSING, "No provider is configured for the queue.");
);

// CLI errors
error_codes!(
(4001, TASK_NOT_FOUND, "Task not found.");
(5001, TASK_NOT_FOUND, "Task not found.");
(5002, GENERATOR_ERROR, "Could not generate code template.");
);

// Db errors
error_codes!(
(5000, GENERAL_DATABASE_ERROR, "A general database error occurred.");
(5001, ENTITY_ALREADY_EXIST, "An entity with the same primary key already exists.");
(5002, ENTITY_DOES_NOT_EXIST, "An entity that was requested does not exist.");
(5003, CONNECTION_AQUIRE, "Database connection could not be acquired.");
(5004, CONNECTION_ERROR, "Something went wrong while connecting to the database.");
(5005, DB_EXECUTION_ERROR, "Could not execute operation successfully.");
(5006, DB_QUERY_ERROR, "Error occurred while performing a query.");
(5007, COULD_NOT_RETRIEVE_LAST_INSERT_ID, "Could not retrieve last insert id.");
(5008, RECORD_NOT_FOUND, "Database record could not be found.");
(5009, DB_CUSTOM_ERROR, "Custom DB error occurred.");
(5010, ATTR_NOT_SET, "Attribute in active model not set.");
(5011, PARSE_VALUE_AS_TARGET_TYPE, "An error occurred while trying to parse a value as a target type.");
(5012, DB_PARSE_JSON, "Could not parse JSON from or to db.");
(5013, MIGRATION_ERROR, "A migration error occurred.");
(5014, RECORDS_NOT_INSERTED, "DB records could not get inserted.");
(5015, RECORDS_NOT_UPDATED, "DB records could nto get updated.");
(6000, GENERAL_DATABASE_ERROR, "A general database error occurred.");
(6001, ENTITY_ALREADY_EXIST, "An entity with the same primary key already exists.");
(6002, ENTITY_DOES_NOT_EXIST, "An entity that was requested does not exist.");
(6003, CONNECTION_AQUIRE, "Database connection could not be acquired.");
(6004, CONNECTION_ERROR, "Something went wrong while connecting to the database.");
(6005, DB_EXECUTION_ERROR, "Could not execute operation successfully.");
(6006, DB_QUERY_ERROR, "Error occurred while performing a query.");
(6007, COULD_NOT_RETRIEVE_LAST_INSERT_ID, "Could not retrieve last insert id.");
(6008, RECORD_NOT_FOUND, "Database record could not be found.");
(6009, DB_CUSTOM_ERROR, "Custom DB error occurred.");
(6010, ATTR_NOT_SET, "Attribute in active model not set.");
(6011, PARSE_VALUE_AS_TARGET_TYPE, "An error occurred while trying to parse a value as a target type.");
(6012, DB_PARSE_JSON, "Could not parse JSON from or to db.");
(6013, MIGRATION_ERROR, "A migration error occurred.");
(6014, RECORDS_NOT_INSERTED, "DB records could not get inserted.");
(6015, RECORDS_NOT_UPDATED, "DB records could nto get updated.");
);

// Auth errors
error_codes!(
(6001, INVALID_JWT, "An invalid JWT was provided.");
(7001, INVALID_JWT, "An invalid JWT was provided.");
);

// Misc Errors
error_codes!(
(99999, CUSTOM_ERROR, "Some kind of unmappable/custom error.");
);

0 comments on commit 2e97e9d

Please sign in to comment.