/* 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 */ use crate::{request_info::RequestInfo, responders::UiPage}; use jellyui::components::message::Message; use rocket::{ Request, catch, http::Status, response::{self, Responder}, }; use serde_json::{Value, json}; use thiserror::Error; #[catch(default)] pub fn r_catch(status: Status, request: &Request) -> UiPage { catch_with_message(&RequestInfo::from_request_ut(request), format!("{status}")) } fn catch_with_message(ri: &RequestInfo, message: String) -> UiPage { ri.respond_ui(&Message { ri: &ri.render_info(), kind: "error", text: &message, }) } #[catch(default)] pub fn r_api_catch(status: Status, _request: &Request) -> Value { json!({ "error": format!("{status}") }) } pub type MyResult = Result; #[derive(Error)] pub enum MyError { #[error("Not authenticated. Please log in.")] NoAuthentication, #[error("{0}")] Other(#[from] anyhow::Error), #[error("{0}")] Io(#[from] std::io::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}") }).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(&RequestInfo::from_request_ut(req), format!("{self:#}")) .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)) } } impl From for MyError { fn from(err: std::fmt::Error) -> MyError { MyError::Other(anyhow::anyhow!("{err}")) } } impl From for MyError { fn from(err: serde_json::Error) -> Self { MyError::Other(anyhow::anyhow!("{err}")) } }