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
// Copyright (C) 2020 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::error::Error as StdError;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;

use hyper::Error as HyperError;
use hyper::http::Error as HttpError;
use hyper::http::StatusCode as HttpStatusCode;
use serde_json::Error as JsonError;


/// An error type that any endpoint related error can be converted into.
///
/// Please note that this error type necessarily looses some information
/// over dealing with the actual endpoint error type.
#[derive(Debug)]
pub enum Error {
  /// An HTTP related error.
  Http(HttpError),
  /// We encountered an HTTP that either represents a failure or is not
  /// supported.
  HttpStatus(HttpStatusCode),
  /// An error reported by the `hyper` crate.
  Hyper(HyperError),
  /// A JSON conversion error.
  Json(JsonError),
}

impl Display for Error {
  fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
    match self {
      Error::Http(err) => write!(fmt, "{}", err),
      Error::HttpStatus(status) => write!(fmt, "HTTP status: {}", status),
      Error::Hyper(err) => write!(fmt, "{}", err),
      Error::Json(err) => write!(fmt, "{}", err),
    }
  }
}

impl StdError for Error {
  fn source(&self) -> Option<&(dyn StdError + 'static)> {
    match self {
      Error::Http(err) => err.source(),
      Error::HttpStatus(..) => None,
      Error::Hyper(err) => err.source(),
      Error::Json(err) => err.source(),
    }
  }
}

impl From<HttpError> for Error {
  fn from(e: HttpError) -> Self {
    Error::Http(e)
  }
}

impl From<HttpStatusCode> for Error {
  fn from(e: HttpStatusCode) -> Self {
    Error::HttpStatus(e)
  }
}

impl From<HyperError> for Error {
  fn from(e: HyperError) -> Self {
    Error::Hyper(e)
  }
}

impl From<JsonError> for Error {
  fn from(e: JsonError) -> Self {
    Error::Json(e)
  }
}