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
use actix_web::http::StatusCode;

use thiserror::Error;

#[cfg(feature = "bigtable")]
use crate::db::bigtable::BigTableError;
use crate::errors::ReportableError;

pub type DbResult<T> = Result<T, DbError>;

#[derive(Debug, Error)]
pub enum DbError {
    #[error("Error while performing (de)serialization: {0}")]
    Serialization(String),

    #[error("Error deserializing to u64: {0}")]
    DeserializeU64(String),

    #[error("Error deserializing to String: {0}")]
    DeserializeString(String),

    #[error("Unable to determine table status")]
    TableStatusUnknown,

    #[cfg(feature = "bigtable")]
    #[error("BigTable error: {0}")]
    BTError(#[from] BigTableError),

    #[error("Connection failure: {0}")]
    ConnectionError(String),

    #[error("The conditional request failed")]
    Conditional,

    #[error("Database integrity error: {}", _0)]
    Integrity(String, Option<String>),

    #[error("Unknown Database Error: {0}")]
    General(String),

    // Return a 503 error
    #[error("Process pending, please wait.")]
    Backoff(String),
}

impl DbError {
    pub fn status(&self) -> StatusCode {
        match self {
            #[cfg(feature = "bigtable")]
            Self::BTError(e) => e.status(),
            Self::Backoff(_) => StatusCode::SERVICE_UNAVAILABLE,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl ReportableError for DbError {
    fn reportable_source(&self) -> Option<&(dyn ReportableError + 'static)> {
        match &self {
            #[cfg(feature = "bigtable")]
            DbError::BTError(e) => Some(e),
            _ => None,
        }
    }

    fn is_sentry_event(&self) -> bool {
        match &self {
            #[cfg(feature = "bigtable")]
            DbError::BTError(e) => e.is_sentry_event(),
            _ => false,
        }
    }

    fn metric_label(&self) -> Option<&'static str> {
        match &self {
            #[cfg(feature = "bigtable")]
            DbError::BTError(e) => e.metric_label(),
            DbError::Backoff(_) => Some("storage.error.backoff"),
            _ => None,
        }
    }

    fn extras(&self) -> Vec<(&str, String)> {
        match &self {
            #[cfg(feature = "bigtable")]
            DbError::BTError(e) => e.extras(),
            DbError::Backoff(e) => {
                vec![("raw", e.to_string())]
            }
            DbError::Integrity(_, Some(row)) => vec![("row", row.clone())],
            _ => vec![],
        }
    }
}