chilli/
types.rs

1//! This module implements a number of types.
2
3use std::collections::HashMap;
4use std::error;
5use std::convert;
6use std::error::Error;
7use std::fmt;
8
9use wrappers::{Request, Response};
10pub use http_errors::HTTPError;
11
12pub use self::PencilError::{
13    PenHTTPError,
14    PenUserError
15};
16
17
18/// The Pencil User Error type.
19#[derive(Clone, Debug)]
20pub struct UserError {
21    pub desc: String,
22}
23
24impl UserError {
25    pub fn new<T>(desc: T) -> UserError where T: AsRef<str> {
26        UserError {
27            desc: desc.as_ref().to_owned(),
28        }
29    }
30}
31
32impl fmt::Display for UserError {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        f.write_str(&self.desc)
35    }
36}
37
38impl error::Error for UserError {
39    fn description(&self) -> &str {
40        &self.desc
41    }
42}
43
44
45/// The Pencil Error type.
46#[derive(Clone, Debug)]
47pub enum PencilError {
48    PenHTTPError(HTTPError),
49    PenUserError(UserError),
50}
51
52impl convert::From<HTTPError> for PencilError {
53    fn from(err: HTTPError) -> PencilError {
54        PenHTTPError(err)
55    }
56}
57
58impl convert::From<UserError> for PencilError {
59    fn from(err: UserError) -> PencilError {
60        PenUserError(err)
61    }
62}
63
64impl fmt::Display for PencilError {
65    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66        match *self {
67            PenHTTPError(ref err) => f.write_str(err.description()),
68            PenUserError(ref err) => f.write_str(err.description()),
69        }
70    }
71}
72
73impl error::Error for PencilError {
74
75    fn description(&self) -> &str {
76        match *self {
77            PenHTTPError(ref err) => err.description(),
78            PenUserError(ref err) => err.description(),
79        }
80    }
81
82    fn cause(&self) -> Option<&error::Error> {
83        match *self {
84            PenHTTPError(ref err) => Some(&*err as &error::Error),
85            PenUserError(_) => None,
86        }
87    }
88}
89
90
91/// The Pencil Result type.
92pub type PencilResult = Result<Response, PencilError>;
93
94
95/// View arguments type.
96pub type ViewArgs = HashMap<String, String>;
97/// View function type.
98pub type ViewFunc = fn(&mut Request) -> PencilResult;
99
100
101/// HTTP Error handler type.
102pub type HTTPErrorHandler = Fn(HTTPError) -> PencilResult + Send + Sync;
103/// User Error handler type.
104pub type UserErrorHandler = Fn(UserError) -> PencilResult + Send + Sync;
105
106/// Before request func type.
107pub type BeforeRequestFunc = Fn(&mut Request) -> Option<PencilResult> + Send + Sync;
108
109
110/// After request func type.
111pub type AfterRequestFunc = Fn(&Request, &mut Response) + Send + Sync;
112
113
114/// Teardown request func type.
115pub type TeardownRequestFunc = Fn(Option<&PencilError>) + Send + Sync;