feat(postgres): Add human-readable Display implementation for errors

This commit is contained in:
Vincent Ambo 2018-12-13 15:01:05 +01:00
parent 68060fea13
commit e801b5853c

View file

@ -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 <E: Into<ErrorKind>> From<E> for Error {
fn from(err: E) -> Error {
Error {
@ -56,11 +83,11 @@ impl From<PgError> for ErrorKind {
/// 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>;
fn context<C: fmt::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> {
fn context<C: fmt::Display>(self, ctx: C) -> Result<T> {
self.map_err(|err| Error {
context: Some(format!("{}", ctx)),
.. err.into()