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
|
//! This module defines custom error types using the `failure`-crate.
//! Links to foreign error types (such as database connection errors)
//! are established in a similar way as was tradition in
//! `error_chain`, albeit manually.
use std::result;
use actix_web::{ResponseError, HttpResponse};
use actix_web::http::StatusCode;
// Modules with foreign errors:
use actix;
use actix_web;
use diesel;
use r2d2;
use reqwest;
use tera;
pub type Result<T> = result::Result<T, ConverseError>;
#[derive(Debug, Fail)]
pub enum ConverseError {
#[fail(display = "an internal Converse error occured: {}", reason)]
InternalError { reason: String },
#[fail(display = "a database error occured: {}", error)]
Database { error: diesel::result::Error },
#[fail(display = "a database connection pool error occured: {}", error)]
ConnectionPool { error: r2d2::Error },
#[fail(display = "a template rendering error occured: {}", reason)]
Template { reason: String },
#[fail(display = "error occured during request handling: {}", error)]
ActixWeb { error: actix_web::Error },
// This variant is used as a catch-all for wrapping
// actix-web-compatible response errors, such as the errors it
// throws itself.
#[fail(display = "Actix response error: {}", error)]
Actix { error: Box<ResponseError> },
}
// Establish conversion links to foreign errors:
impl From<diesel::result::Error> for ConverseError {
fn from(error: diesel::result::Error) -> ConverseError {
ConverseError::Database { error }
}
}
impl From<r2d2::Error> for ConverseError {
fn from(error: r2d2::Error) -> ConverseError {
ConverseError::ConnectionPool { error }
}
}
impl From<tera::Error> for ConverseError {
fn from(error: tera::Error) -> ConverseError {
ConverseError::Template {
reason: format!("{}", error),
}
}
}
impl From<actix::MailboxError> for ConverseError {
fn from(error: actix::MailboxError) -> ConverseError {
ConverseError::Actix { error: Box::new(error) }
}
}
impl From<actix_web::Error> for ConverseError {
fn from(error: actix_web::Error) -> ConverseError {
ConverseError::ActixWeb { error }
}
}
impl From<reqwest::Error> for ConverseError {
fn from(error: reqwest::Error) -> ConverseError {
ConverseError::InternalError {
reason: format!("Failed to make HTTP request: {}", error),
}
}
}
// Support conversion of error type into HTTP error responses:
impl ResponseError for ConverseError {
fn error_response(&self) -> HttpResponse {
// Everything is mapped to internal server errors for now.
HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR)
.body(format!("An error occured: {}", self))
}
}
|