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
use actix_http::ws::HandshakeError;
use actix_web::{error::ResponseError, http::StatusCode, HttpResponse};
use serde_json::json;

use autopush_common::errors::ReportableError;

/// The main error type
#[derive(thiserror::Error, Debug)]
pub enum ApiError {
    #[error("Actix Web error: {0}")]
    Actix(#[from] actix_web::error::Error),

    #[error("LogCheck")]
    LogCheck,
}

impl ResponseError for ApiError {
    fn status_code(&self) -> StatusCode {
        match self {
            ApiError::Actix(e) => e.as_response_error().status_code(),
            ApiError::LogCheck => StatusCode::IM_A_TEAPOT,
        }
    }

    fn error_response(&self) -> HttpResponse {
        let code = self.status_code();
        HttpResponse::build(code).json(json!({
            "code": code.as_u16(),
            "errno": self.errno(),
            "error": self.to_string(),
        }))
    }
}

impl ReportableError for ApiError {
    fn is_sentry_event(&self) -> bool {
        match self {
            // Ignore failing upgrade to WebSocket
            ApiError::Actix(e) => e.as_error::<HandshakeError>().is_none(),
            _ => true,
        }
    }
}

impl ApiError {
    /// Return a unique errno code per variant
    pub fn errno(&self) -> i32 {
        match self {
            ApiError::Actix(_) => 500,
            ApiError::LogCheck => 999,
        }
    }
}