2024-11-13 20:00:15 +00:00
|
|
|
use std::fmt::Display;
|
|
|
|
|
2024-11-14 17:59:21 +00:00
|
|
|
use poem::{error::ResponseError, http::StatusCode};
|
|
|
|
use sqlx::postgres::PgDatabaseError;
|
|
|
|
|
2024-11-13 20:00:15 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Error {
|
|
|
|
IOError(std::io::Error),
|
|
|
|
TOMLError(toml::de::Error),
|
2024-11-14 17:59:21 +00:00
|
|
|
SQLError(String),
|
|
|
|
DatabaseError(sqlx::Error),
|
|
|
|
NotFound,
|
|
|
|
MissingField,
|
2024-11-13 20:00:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Display for Error {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
2024-11-14 17:59:21 +00:00
|
|
|
Error::SQLError(error) => write!(f, "SQL Error: {}", error),
|
2024-11-13 20:00:15 +00:00
|
|
|
Error::IOError(error) => write!(f, "IO Error: {}", error),
|
|
|
|
Error::TOMLError(error) => write!(f, "TOML deserialization error: {}", error),
|
2024-11-14 17:59:21 +00:00
|
|
|
Error::DatabaseError(error) => write!(f, "database error: {}", error),
|
|
|
|
Error::NotFound => write!(f, "not found"),
|
|
|
|
Error::MissingField => write!(f, "missing field in row"),
|
2024-11-13 20:00:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::error::Error for Error {}
|
|
|
|
|
2024-11-14 17:59:21 +00:00
|
|
|
impl ResponseError for Error {
|
|
|
|
fn status(&self) -> poem::http::StatusCode {
|
|
|
|
match self {
|
|
|
|
Error::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Error::TOMLError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Error::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Error::NotFound => StatusCode::NOT_FOUND,
|
|
|
|
Error::SQLError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Error::MissingField => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-13 20:00:15 +00:00
|
|
|
impl From<std::io::Error> for Error {
|
|
|
|
fn from(e: std::io::Error) -> Self {
|
|
|
|
Self::IOError(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<toml::de::Error> for Error {
|
|
|
|
fn from(e: toml::de::Error) -> Self {
|
|
|
|
Self::TOMLError(e)
|
|
|
|
}
|
|
|
|
}
|
2024-11-14 17:59:21 +00:00
|
|
|
|
|
|
|
impl From<sqlx::Error> for Error {
|
|
|
|
fn from(e: sqlx::Error) -> Self {
|
|
|
|
match e {
|
|
|
|
sqlx::Error::Database(database_error) => {
|
|
|
|
let error = database_error.downcast::<PgDatabaseError>();
|
|
|
|
match error.code() {
|
|
|
|
code => Error::SQLError(code.to_string()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
sqlx::Error::RowNotFound => Error::NotFound,
|
|
|
|
_ => Self::DatabaseError(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|