summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 100556412c7a0b391b87ec006973d9674d0d9e6f (plain)
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
use std;
use std::fmt;
use std::convert::From;
use rusqlite;
use iron::{IronError, status};
use iron::headers::ContentType;
use iron::modifiers::Header;

#[derive(Debug)]
pub enum LinoError {
    DbError(rusqlite::Error),
    IoError(std::io::Error),
    NotFound(String),
    BadRequest(String),
}

pub type Result<T> = std::result::Result<T, LinoError>;

impl fmt::Display for LinoError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            LinoError::DbError(ref err) => err.fmt(f),
            LinoError::IoError(ref err) => err.fmt(f),
            LinoError::NotFound(ref x) => write!(f, "Could not find {}", x),
            LinoError::BadRequest(ref x) => write!(f, "Bad request: {}", x),
        }
    }
}

impl std::error::Error for LinoError {
    fn description(&self) -> &str {
        match *self {
            LinoError::DbError(ref err) => err.description(),
            LinoError::IoError(ref err) => err.description(),
            LinoError::NotFound(_) => "not found",
            LinoError::BadRequest(_) => "bad request",
        }
    }

    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            LinoError::DbError(ref err) => Some(err),
            LinoError::IoError(ref err) => Some(err),
            LinoError::NotFound(_) => None,
            LinoError::BadRequest(_) => None,
        }
    }
}

impl From<rusqlite::Error> for LinoError {
    fn from(err: rusqlite::Error) -> LinoError {
        LinoError::DbError(err)
    }
}

impl From<std::io::Error> for LinoError {
    fn from(err: std::io::Error) -> LinoError {
        LinoError::IoError(err)
    }
}

impl From<LinoError> for IronError {
    fn from(err: LinoError) -> IronError {
        let code = match err {
            LinoError::NotFound(_) => status::NotFound,
            LinoError::BadRequest(_) => status::BadRequest,
            _ => status::InternalServerError,
        };
        let description = format!("{:?}", err);
        IronError::new(err, (code, Header(ContentType::html()), description))
    }
}