errors.rs 1.22 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
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
use serde::Serialize;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket_contrib::json::Json;


#[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()
    }
}