diff options
author | Vincent Ambo <mail@tazj.in> | 2018-12-13T13·40+0100 |
---|---|---|
committer | Vincent Ambo <mail@tazj.in> | 2018-12-13T13·40+0100 |
commit | 68060fea13cdc26568b1a51e1bf4326885c23d63 (patch) | |
tree | 5351252428d9a0c5f43b37fad68d17006462a1c9 /finito-postgres/src/error.rs | |
parent | 43f71ae82fa6d68abb0486601d9477b82fb42628 (diff) |
feat(postgres): Introduce chained error variants
Introduces error variants for external crate errors and internal errors. Additional context can be provided at sites where errors occur using a simple `.context()` call.
Diffstat (limited to 'finito-postgres/src/error.rs')
-rw-r--r-- | finito-postgres/src/error.rs | 62 |
1 files changed, 61 insertions, 1 deletions
diff --git a/finito-postgres/src/error.rs b/finito-postgres/src/error.rs index 0fb30a99dcd7..aacc219f0418 100644 --- a/finito-postgres/src/error.rs +++ b/finito-postgres/src/error.rs @@ -2,8 +2,68 @@ //! occur while dealing with persisted state machines. use std::result; +use std::fmt::Display; +use uuid::Uuid; + +// errors to chain: +use serde_json::Error as JsonError; +use postgres::Error as PgError; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] -pub enum Error { SomeError } +pub struct Error { + pub kind: ErrorKind, + pub context: Option<String>, +} + +#[derive(Debug)] +pub enum ErrorKind { + /// Errors occuring during JSON serialization of FSM types. + Serialization(String), + + /// Errors occuring during communication with the database. + Database(String), + + /// State machine could not be found. + FSMNotFound(Uuid), + + /// Action could not be found. + ActionNotFound(Uuid), +} + +impl <E: Into<ErrorKind>> From<E> for Error { + fn from(err: E) -> Error { + Error { + kind: err.into(), + context: None, + } + } +} + +impl From<JsonError> for ErrorKind { + fn from(err: JsonError) -> ErrorKind { + ErrorKind::Serialization(err.to_string()) + } +} + +impl From<PgError> for ErrorKind { + fn from(err: PgError) -> ErrorKind { + ErrorKind::Database(err.to_string()) + } +} + +/// Helper trait that makes it possible to supply contextual +/// information with an error. +pub trait ResultExt<T> { + fn context<C: Display>(self, ctx: C) -> Result<T>; +} + +impl <T, E: Into<Error>> ResultExt<T> for result::Result<T, E> { + fn context<C: Display>(self, ctx: C) -> Result<T> { + self.map_err(|err| Error { + context: Some(format!("{}", ctx)), + .. err.into() + }) + } +} |