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 oas_common::{DecodingError, MissingRefsError};
use std::fmt;
use thiserror::Error;

use super::types::ErrorDetails;

#[derive(Error, Debug)]
pub enum CouchError {
    #[error("HTTP: {0}")]
    Http(reqwest::Error),
    #[error("CouchDB: {1}")]
    Couch(reqwest::StatusCode, ErrorDetails),
    #[error("Serialization: {0}")]
    Json(#[from] serde_json::Error),
    #[error("IO: {0}")]
    IO(#[from] std::io::Error),
    #[error("Other: {0}")]
    DecodingError(#[from] DecodingError),
    #[error("{0}")]
    Other(String),
    #[error("{0}")]
    MissingRefs(#[from] MissingRefsError),
    #[error("CouchDB is not reachable")]
    ServiceUnavailable,
    #[error("Not found")]
    NotFound,
}

impl CouchError {
    pub fn status_code(&self) -> Option<u16> {
        match self {
            Self::Http(err) => err.status().map(|s| s.as_u16()),
            Self::Couch(status, _) => Some((*status).into()),
            _ => None,
        }
    }
}

impl From<reqwest::Error> for CouchError {
    fn from(err: reqwest::Error) -> Self {
        Self::Http(err)
    }
}

impl std::error::Error for ErrorDetails {}

impl fmt::Display for ErrorDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(id) = &self.id {
            write!(f, "{} (reason: {}, id {})", self.error, self.reason, id)
        } else {
            write!(f, "{} (reason: {})", self.error, self.reason)
        }
    }
}