errors.rs 1.87 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
1
2
3
4
5
use serde::Serialize;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket_contrib::json::Json;
6
use crate::models::users::UserError;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
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

#[derive(Serialize, Debug)]
pub struct ErrorResponse<T> {
    #[serde(with = "StatusDef")]
    #[serde(flatten)]
    pub status: Status,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<T>
}


#[derive(Serialize)]
#[serde(remote = "Status")]
struct StatusDef {
    code: u16,
    #[serde(rename = "status")]
    reason: &'static str,
}


impl<T> ErrorResponse<T> {
    pub fn new(status: Status, message: String) -> ErrorResponse<T> {
        ErrorResponse {
            status,
            message,
            details: None,
        }
    }

    pub fn with_details(self, details: T) -> ErrorResponse<T> {
        ErrorResponse {
            details: Some(details),
            ..self
        }
    }

    pub fn err<R>(self) -> Result<R, ErrorResponse<T>> {
        Err(self)
    }
}


impl<'r, T: Serialize> Responder<'r> for ErrorResponse<T> {
    fn respond_to(self, req: &Request) -> response::Result<'r> {
        let status = self.status;
        Response::build_from(Json(self).respond_to(req)?).status(status).ok()
    }
}
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

impl From<UserError> for ErrorResponse<()> {
    fn from(e: UserError) -> Self {
        match e {
            UserError::NotFound => ErrorResponse::new(Status::Unauthorized, "Incorrect password or username.".into()),
            UserError::UserExists => ErrorResponse::new(Status::Conflict, "User already exists.".into()),
            UserError::DbError(e) => make_500(e),
            UserError::PasswordError(e) => make_500(e)
        }
    }
}

fn make_500<E: std::fmt::Debug>(e: E) -> ErrorResponse<()> {
    println!("{:?}", e);
    ErrorResponse::new(Status::InternalServerError, "An unexpected error occured.".into())
}