1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
use crate::core::context::Context; use std::error::Error as StdError; pub struct ThrusterError<C> { pub context: C, pub message: String, pub status: u32, pub cause: Option<Box<dyn StdError>>, } pub trait Error<C> { fn build_context(self) -> C; } impl<C: Context> Error<C> for ThrusterError<C> { fn build_context(self) -> C { self.context } } pub trait ErrorSet<C> { fn parsing_error(context: C, error: &str) -> ThrusterError<C>; fn generic_error(context: C) -> ThrusterError<C>; fn unauthorized_error(context: C) -> ThrusterError<C>; fn not_found_error(context: C) -> ThrusterError<C>; } impl<C: Context> ErrorSet<C> for ThrusterError<C> { fn parsing_error(context: C, error: &str) -> ThrusterError<C> { ThrusterError { context, message: format!("Failed to parse '{}'", error), status: 400, cause: None, } } fn generic_error(context: C) -> ThrusterError<C> { ThrusterError { context, message: "Something didn't work!".to_string(), status: 400, cause: None, } } fn unauthorized_error(context: C) -> ThrusterError<C> { ThrusterError { context, message: "Unauthorized".to_string(), status: 401, cause: None, } } fn not_found_error(context: C) -> ThrusterError<C> { ThrusterError { context, message: "Not found".to_string(), status: 404, cause: None, } } } impl<C> std::fmt::Debug for ThrusterError<C> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ThrusterError") .field("message", &self.message) .field("status", &self.status) .finish() } } impl<C: Clone> Clone for ThrusterError<C> { fn clone(&self) -> Self { ThrusterError { context: self.context.clone(), message: self.message.clone(), status: self.status, cause: None, } } }