Move error handling into utils

This commit is contained in:
Elnu 2023-08-08 15:11:31 -07:00
parent 7c043e8357
commit ef562fe656
7 changed files with 52 additions and 28 deletions

View file

@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
utils = { path = "../utils" }
utils = { path = "../utils", features = [ "nothuman" ] }
actix-web = "4.3.1"
derive_more = "0.99.17"
mime = "0.3.17"

View file

@ -1,42 +0,0 @@
use actix_web::{HttpResponse, ResponseError};
use derive_more::From;
use std::fmt::{self, Display};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(From, Debug)]
pub enum Error {
TatoebaApi(reqwest::Error),
NotHuman { target: String },
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl ResponseError for Error {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
use Error::*;
match self {
// 503 Service Unavailable
TatoebaApi(error) => error.status().unwrap_or(StatusCode::SERVICE_UNAVAILABLE),
// 403 Forbidden
NotHuman { .. } => StatusCode::FORBIDDEN,
}
}
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
HttpResponse::build(self.status_code()).body(match self {
Self::NotHuman { target } => format!(
"It looks like you're accessing the Tatoeba API proxy from a script!\n\
Tatoeba CORS restrictions do not apply outside of browsers, so please access the API directly:\n\
{target}\n\
If you feel this is mistake, please open an issue:\n\
https://codeberg.org/ElnuDev/tatoeba-api-rs"),
_ => self.to_string(),
})
}
}

View file

@ -1,7 +1,4 @@
mod error;
pub use error::{Error, Result};
use utils::is_human;
use utils::{error::{Error, Result}, is_human};
use actix_web::{get, http::header, App, HttpRequest, HttpResponse, HttpServer, Responder};