about summary refs log tree commit diff
path: root/finito-postgres/src/error.rs
blob: 0bf7f4018591de3374567323ee3fd6ad7a999d7d (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//! This module defines error types and conversions for issue that can
//! occur while dealing with persisted state machines.

use std::result;
use std::fmt;
use uuid::Uuid;
use std::error::Error as StdError;

// 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 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 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 {
            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: fmt::Display>(self, ctx: C) -> Result<T>;
}

impl <T, E: Into<Error>> ResultExt<T> for result::Result<T, E> {
    fn context<C: fmt::Display>(self, ctx: C) -> Result<T> {
        self.map_err(|err| Error {
            context: Some(format!("{}", ctx)),
            .. err.into()
        })
    }
}