hotshot_query_service/
error.rs

1// Copyright (c) 2022 Espresso Systems (espressosys.com)
2// This file is part of the HotShot Query Service library.
3//
4// This program is free software: you can redistribute it and/or modify it under the terms of the GNU
5// General Public License as published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9// General Public License for more details.
10// You should have received a copy of the GNU General Public License along with this program. If not,
11// see <https://www.gnu.org/licenses/>.
12
13use std::fmt::Display;
14
15use derive_more::From;
16use serde::{Deserialize, Serialize};
17use snafu::Snafu;
18use tide_disco::StatusCode;
19
20use crate::{availability, explorer, merklized_state, node, status};
21
22#[derive(Clone, Debug, From, Snafu, Deserialize, Serialize)]
23pub enum Error {
24    #[snafu(display("{source}"))]
25    Availability { source: availability::Error },
26    #[snafu(display("{source}"))]
27    Node { source: node::Error },
28    #[snafu(display("{source}"))]
29    Status { source: status::Error },
30    #[snafu(display("{source}"))]
31    MerklizedState { source: merklized_state::Error },
32    #[snafu(display("{source}"))]
33    Explorer {
34        #[serde(rename = "error")]
35        source: explorer::Error,
36    },
37    #[snafu(display("error {status}: {message}"))]
38    Custom { message: String, status: StatusCode },
39}
40
41impl Error {
42    pub fn internal<M: Display>(message: M) -> Self {
43        Self::Custom {
44            message: message.to_string(),
45            status: StatusCode::INTERNAL_SERVER_ERROR,
46        }
47    }
48}
49
50impl tide_disco::Error for Error {
51    fn catch_all(status: StatusCode, message: String) -> Self {
52        Self::Custom { status, message }
53    }
54
55    fn status(&self) -> StatusCode {
56        match self {
57            Self::Availability { source } => source.status(),
58            Self::Node { source } => source.status(),
59            Self::Status { source } => source.status(),
60            Self::MerklizedState { source } => source.status(),
61            Self::Explorer { source } => source.status(),
62            Self::Custom { status, .. } => *status,
63        }
64    }
65}