iota_rest_kv/
errors.rs

1// Copyright (c) 2025 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4//! This module includes the error types the REST API sends back to the client.
5
6use axum::{
7    Json,
8    http::StatusCode,
9    response::{IntoResponse, Response},
10};
11use serde::Serialize;
12use thiserror::Error;
13
14/// An Error type which represents the possible errors the REST API server can
15/// send back to the client.
16#[derive(Error, Debug)]
17pub enum ApiError {
18    #[error("bad request: {0}")]
19    BadRequest(String),
20    #[error("not found")]
21    NotFound,
22    #[error("internal server error")]
23    InternalServerError,
24}
25
26impl IntoResponse for ApiError {
27    fn into_response(self) -> Response {
28        let status_code = match self {
29            ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
30            ApiError::NotFound => StatusCode::NOT_FOUND,
31            ApiError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
32        };
33
34        let body = Json(ErrorResponse {
35            error_code: status_code.as_u16().to_string(),
36            error_message: self.to_string(),
37        });
38
39        (status_code, body).into_response()
40    }
41}
42
43/// Describes the response body of a unsuccessful HTTP request.
44#[derive(Clone, Debug, Serialize)]
45pub(crate) struct ErrorResponse {
46    error_code: String,
47    error_message: String,
48}