Skip to main content

chc_service/
error.rs

1use axum::{http::StatusCode, response::IntoResponse};
2use holochain::prelude::PrevActionError;
3
4#[derive(Debug, thiserror::Error)]
5pub enum ChcServiceError {
6    #[error("Hash was nout found in the CHC")]
7    HashNotFound(String),
8    #[error("Bad request error: {}", 0)]
9    BadRequest(String),
10    #[error("Invalid record input: {}", 0)]
11    InvalidRecordInput(u32),
12    #[error(transparent)]
13    InvalidChain(#[from] PrevActionError),
14    #[error(transparent)]
15    InternalError(#[from] anyhow::Error),
16}
17
18impl IntoResponse for ChcServiceError {
19    fn into_response(self) -> axum::response::Response {
20        match self {
21            Self::HashNotFound(message) => {
22                tracing::error!("Hash was nout foundin the CHC");
23                e498(message)
24            }
25            Self::BadRequest(body_text) => {
26                tracing::error!("Bad request error: {}", body_text);
27                (
28                    StatusCode::BAD_REQUEST,
29                    format!("Bad request error: {}", body_text),
30                )
31                    .into_response()
32            }
33            Self::InvalidRecordInput(seq) => {
34                tracing::error!("Invalid record input: {}", seq);
35                e498(seq)
36            }
37            Self::InvalidChain(e) => {
38                // local chain is out of sync with CHC
39                // call get_record_data instead of adding record
40                tracing::error!("Invalid chain error: {}", e);
41                (
42                    StatusCode::from_u16(409).unwrap(),
43                    rmp_serde::to_vec("Local chain is out of sync with the CHC")
44                        .expect("Failed to serialize to MessagePack"),
45                )
46                    .into_response()
47            }
48            Self::InternalError(e) => {
49                tracing::error!("Internal server error: {}", e);
50                (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
51            }
52        }
53    }
54}
55
56fn e498<T: serde::Serialize>(value: T) -> axum::response::Response {
57    (
58        StatusCode::from_u16(498).unwrap(),
59        rmp_serde::to_vec(&value).expect("Failed to serialize MessagePack"),
60    )
61        .into_response()
62}