Want to contribute? Fork me on Codeberg.org!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.6 KiB

use crate::Database;
2 years ago
use actix_web::{error::BlockingError, HttpResponse};
use derive_more::From;
use sanitize_html::errors::SanitizeError;
2 years ago
use std::{
string::FromUtf8Error,
sync::{MutexGuard, PoisonError},
};
use validator::ValidationErrors;
#[derive(From, Debug)]
pub enum Error {
InvalidOrigin,
InvalidBodyEncoding(FromUtf8Error),
InvalidBodyJson(serde_json::Error),
InvalidUrl,
InvalidFields(ValidationErrors),
InvalidContentId,
InvalidParent,
EmailRequired,
NameRequired,
DatabaseAccessBlockingError(BlockingError),
DatabaseAccessPoisonError,
DatabaseInternalError(rusqlite::Error),
SanitizationError(SanitizeError),
PageFetchError(reqwest::Error),
}
impl Error {
pub fn to_http_response(&self) -> HttpResponse {
match self {
Self::InvalidOrigin
| Self::InvalidBodyEncoding(_)
| Self::InvalidBodyJson(_)
| Self::InvalidUrl
| Self::InvalidFields(_)
| Self::InvalidContentId
| Self::InvalidParent
| Self::EmailRequired
| Self::NameRequired => HttpResponse::BadRequest(),
Self::DatabaseAccessBlockingError(_)
| Self::DatabaseAccessPoisonError
| Self::DatabaseInternalError(_)
| Self::SanitizationError(_)
| Self::PageFetchError(_) => {
eprintln!("{:?}", self);
HttpResponse::InternalServerError()
2 years ago
}
}
.reason(match self {
Self::InvalidOrigin => "invalid request origin",
2 years ago
Self::InvalidBodyEncoding(_) | Self::InvalidBodyJson(_) => "invalid request body",
Self::InvalidUrl => "invalid request url",
Self::InvalidFields(_) => "invalid request field",
Self::InvalidContentId => "invalid request content id",
Self::InvalidParent => "invalid comment parent",
Self::EmailRequired => "comment email required",
Self::NameRequired => "comment name required",
2 years ago
Self::DatabaseAccessBlockingError(_) | Self::DatabaseAccessPoisonError => {
"database access error"
}
Self::DatabaseInternalError(_) => "database internal error",
Self::SanitizationError(_) => "comment sanitization error",
Self::PageFetchError(_) => "page fetch error",
})
.finish()
}
}
impl<'a> From<PoisonError<MutexGuard<'a, Database>>> for Error {
fn from(_: PoisonError<MutexGuard<'a, Database>>) -> Self {
Self::DatabaseAccessPoisonError
}
}