diff options
Diffstat (limited to 'server/src/routes/error.rs')
| -rw-r--r-- | server/src/routes/error.rs | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/server/src/routes/error.rs b/server/src/routes/error.rs new file mode 100644 index 0000000..578d841 --- /dev/null +++ b/server/src/routes/error.rs @@ -0,0 +1,75 @@ +/* + This file is part of jellything (https://codeberg.org/metamuffin/jellything) + which is licensed under the GNU Affero General Public License (version 3); see /COPYING. + Copyright (C) 2026 metamuffin <metamuffin.org> +*/ +use rocket::{ + Request, catch, + http::Status, + response::{self, Responder, content::RawHtml}, +}; +use serde_json::{Value, json}; +use std::fmt::Display; + +#[catch(default)] +pub fn r_catch(status: Status, _request: &Request) -> RawHtml<String> { + catch_with_message(format!("{status}")) +} +fn catch_with_message(message: String) -> RawHtml<String> { + RawHtml(message) // TODO +} + +#[catch(default)] +pub fn r_api_catch(status: Status, _request: &Request) -> Value { + json!({ "error": format!("{status}") }) +} + +pub type MyResult<T> = Result<T, MyError>; + +// TODO an actual error enum would be useful for status codes + +pub struct MyError(pub anyhow::Error); + +impl<'r> Responder<'r, 'static> for MyError { + fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> { + match req.accept().map(|a| a.preferred()) { + Some(x) if x.is_json() => json!({ "error": format!("{}", self.0) }).respond_to(req), + // Some(x) if x.is_avif() || x.is_png() || x.is_jpeg() => { + // (ContentType::AVIF, ERROR_IMAGE.as_slice()).respond_to(req) + // } + _ => catch_with_message(format!("{:#}", self.0)).respond_to(req), + } + } +} + +impl std::fmt::Debug for MyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("{:?}", self.0)) + } +} + +impl Display for MyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} +impl From<anyhow::Error> for MyError { + fn from(err: anyhow::Error) -> MyError { + MyError(err) + } +} +impl From<std::fmt::Error> for MyError { + fn from(err: std::fmt::Error) -> MyError { + MyError(anyhow::anyhow!("{err}")) + } +} +impl From<std::io::Error> for MyError { + fn from(err: std::io::Error) -> Self { + MyError(anyhow::anyhow!("{err}")) + } +} +impl From<serde_json::Error> for MyError { + fn from(err: serde_json::Error) -> Self { + MyError(anyhow::anyhow!("{err}")) + } +} |