From e801b5853c1d06d1dc5cb43eadba0069b7e6fa85 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Thu, 13 Dec 2018 15:01:05 +0100 Subject: feat(postgres): Add human-readable Display implementation for errors --- finito-postgres/src/error.rs | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/finito-postgres/src/error.rs b/finito-postgres/src/error.rs index aacc219f0418..0bf7f4018591 100644 --- a/finito-postgres/src/error.rs +++ b/finito-postgres/src/error.rs @@ -2,8 +2,9 @@ //! occur while dealing with persisted state machines. use std::result; -use std::fmt::Display; +use std::fmt; use uuid::Uuid; +use std::error::Error as StdError; // errors to chain: use serde_json::Error as JsonError; @@ -32,6 +33,32 @@ pub enum ErrorKind { ActionNotFound(Uuid), } +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use ErrorKind::*; + let msg = match &self.kind { + Serialization(err) => + format!("JSON serialization error: {}", err), + + Database(err) => + format!("PostgreSQL error: {}", err), + + FSMNotFound(id) => + format!("FSM with ID {} not found", id), + + ActionNotFound(id) => + format!("Action with ID {} not found", id), + }; + + match &self.context { + None => write!(f, "{}", msg), + Some(ctx) => write!(f, "{}: {}", ctx, msg), + } + } +} + +impl StdError for Error {} + impl > From for Error { fn from(err: E) -> Error { Error { @@ -56,11 +83,11 @@ impl From for ErrorKind { /// Helper trait that makes it possible to supply contextual /// information with an error. pub trait ResultExt { - fn context(self, ctx: C) -> Result; + fn context(self, ctx: C) -> Result; } impl > ResultExt for result::Result { - fn context(self, ctx: C) -> Result { + fn context(self, ctx: C) -> Result { self.map_err(|err| Error { context: Some(format!("{}", ctx)), .. err.into() -- cgit 1.4.1