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
use std::borrow::Cow; /// Use this for most non-specific errors. /// /// Refer to [`doc/errors.md`](../../doc/errors/) for more details. /// /// # Examples /// /// ```no_run /// # #![feature(plugin)] /// # #![plugin(rocket_codegen)] /// # extern crate sudoku_backend; /// # #[macro_use] /// # extern crate rocket; /// # use rocket::response::content::Json; /// # use sudoku_backend::ops::errors::{GenericErrorSeverity, GenericError}; /// # fn work() -> Result<String, &'static str> { /// # Err("henlo") /// # } /// #[get("/endpoint")] /// fn endpoint() -> Result<String, Json<GenericError>> { /// work().map_err(|e| Json(GenericError { /// reason: format!("couldn't finish work: {}", e).into(), /// severity: GenericErrorSeverity::Warning, /// })) /// } /// /// fn main() { /// rocket::ignite() /// .mount("/", routes![endpoint]) /// .launch(); /// } /// ``` #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct GenericError { /// In all-lowercase past-tense finishing-punctuation-free form. /// /// For example: "failed to apply diff", "user with that name exists". pub reason: Cow<'static, str>, /// How bad the error is. pub severity: GenericErrorSeverity, } /// How severe an error is. /// /// Refer to [`doc/errors.md`](../../doc/errors/) for more details. #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] #[serde(rename_all = "lowercase")] pub enum GenericErrorSeverity { /// Something went wrong, usually user's fault. Warning, /// Some invariant failed, usually internal DB failure or a malicious API call. Danger, } impl GenericErrorSeverity { /// The currently-lowest severity, for generic code. #[allow(non_upper_case_globals)] pub const Lowest: GenericErrorSeverity = GenericErrorSeverity::Warning; } impl<R: Into<Cow<'static, str>>> From<(R, GenericErrorSeverity)> for GenericError { fn from((r, s): (R, GenericErrorSeverity)) -> GenericError { GenericError { reason: r.into(), severity: s, } } }