feat(postgres): Add human-readable Display implementation for errors
This commit is contained in:
parent
68060fea13
commit
e801b5853c
1 changed files with 30 additions and 3 deletions
|
@ -2,8 +2,9 @@
|
||||||
//! occur while dealing with persisted state machines.
|
//! occur while dealing with persisted state machines.
|
||||||
|
|
||||||
use std::result;
|
use std::result;
|
||||||
use std::fmt::Display;
|
use std::fmt;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
use std::error::Error as StdError;
|
||||||
|
|
||||||
// errors to chain:
|
// errors to chain:
|
||||||
use serde_json::Error as JsonError;
|
use serde_json::Error as JsonError;
|
||||||
|
@ -32,6 +33,32 @@ pub enum ErrorKind {
|
||||||
ActionNotFound(Uuid),
|
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 {
|
impl <E: Into<ErrorKind>> From<E> for Error {
|
||||||
fn from(err: E) -> Error {
|
fn from(err: E) -> Error {
|
||||||
Error {
|
Error {
|
||||||
|
@ -56,11 +83,11 @@ impl From<PgError> for ErrorKind {
|
||||||
/// Helper trait that makes it possible to supply contextual
|
/// Helper trait that makes it possible to supply contextual
|
||||||
/// information with an error.
|
/// information with an error.
|
||||||
pub trait ResultExt<T> {
|
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> {
|
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 {
|
self.map_err(|err| Error {
|
||||||
context: Some(format!("{}", ctx)),
|
context: Some(format!("{}", ctx)),
|
||||||
.. err.into()
|
.. err.into()
|
||||||
|
|
Loading…
Add table
Reference in a new issue