Skip to main content

feldera_types/
error.rs

1use actix_web::ResponseError;
2use actix_web::http::StatusCode;
3use log::{error, info};
4use serde::{Deserialize, Serialize};
5use serde_json::Value as JsonValue;
6use std::{borrow::Cow, error::Error as StdError};
7use tracing::Level;
8use utoipa::ToSchema;
9pub const MAX_REPORTED_PARSE_ERRORS: usize = 1_000;
10
11/// Information returned by REST API endpoints on error.
12#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
13pub struct ErrorResponse {
14    /// Human-readable error message.
15    #[schema(example = "Explanation of the error that occurred.")]
16    pub message: String,
17    /// Error code is a string that specifies this error type.
18    #[schema(example = "CodeSpecifyingErrorType")]
19    pub error_code: Cow<'static, str>,
20    /// Detailed error metadata.
21    /// The contents of this field is determined by `error_code`.
22    #[schema(value_type = Value)]
23    pub details: JsonValue,
24}
25
26/// Error trait which internal errors must implement such that it
27/// can be transformed to a complete JSON error response.
28///
29/// An error that is also an HTTP response, an actix `ResponseError`, converts to an
30/// [`ErrorResponse`] that is logged by its status code.
31pub trait DetailedError: StdError + Serialize {
32    /// Identifying name of the error.
33    fn error_code(&self) -> Cow<'static, str>;
34
35    /// The level to log the error at.
36    fn log_level(&self) -> Level {
37        Level::ERROR
38    }
39}
40
41/// An error from the engine that runs a pipeline's circuit, where the engine's own error type
42/// is unknown: inside the pipeline controller's errors. It reports what a [`DetailedError`]
43/// reports, and it serializes behind a pointer.
44pub trait EngineError: StdError + erased_serde::Serialize + Send + Sync + 'static {
45    /// Identifying name of the error, as [`DetailedError::error_code`] gives it.
46    fn error_code(&self) -> Cow<'static, str>;
47
48    /// The kind of the I/O error that caused this error, if an I/O error did.
49    fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
50        None
51    }
52}
53
54erased_serde::serialize_trait_object!(EngineError);
55
56impl<E> From<&E> for ErrorResponse
57where
58    E: DetailedError + ResponseError,
59{
60    /// Transform the detailed error to a complete JSON error response.
61    /// - The message is retrieved using `to_string()` (available due to trait `StdError`)
62    /// - The status code determines the level of the log statement during this function
63    ///   (available due to trait `ResponseError`)
64    /// - The details are retrieved by serializing to JSON (available due to trait `Serialize`)
65    fn from(error: &E) -> ErrorResponse {
66        Self::from_error(error)
67    }
68}
69
70impl ErrorResponse {
71    pub fn from_error<E>(error: &E) -> Self
72    where
73        E: DetailedError + ResponseError,
74    {
75        // Transform the error into a response
76        let response = Self::from_error_nolog(error);
77
78        // Log based on the status code
79        if error.status_code().is_success() {
80            // The status code should not be successful for an error response
81            error!(
82                "[HTTP error (caused by implementation)] expected error but got success status code {} {}: {}",
83                error.status_code(),
84                response.error_code,
85                response.message
86            );
87        } else if error.status_code().is_client_error() {
88            // Client-caused error responses
89            info!(
90                "[HTTP error (caused by client)] {} {}: {}",
91                error.status_code(),
92                response.error_code,
93                response.message
94            );
95        } else if error.status_code() == StatusCode::SERVICE_UNAVAILABLE {
96            info!(
97                "[HTTP error] {} {}: {}",
98                error.status_code(),
99                response.error_code,
100                response.message
101            );
102        } else {
103            // All other status responses should not occur in the implementation,
104            // and thus are logged as errors. Many of the implementation errors are
105            // represented as Internal Server Errors (500).
106            error!(
107                "[HTTP error (caused by implementation)] {} {}: {}",
108                error.status_code(),
109                response.error_code,
110                response.message
111            );
112        }
113
114        // Print error backtrace if available for an internal server error
115        if error.status_code() == StatusCode::INTERNAL_SERVER_ERROR
116            && let Some(backtrace) = response
117                .details
118                .get("backtrace")
119                .and_then(JsonValue::as_str)
120        {
121            error!("Error backtrace:\n{backtrace}");
122        }
123
124        response
125    }
126
127    pub fn from_error_nolog<E>(error: &E) -> Self
128    where
129        E: DetailedError,
130    {
131        let message = error.to_string();
132        let error_code = error.error_code();
133        let details = serde_json::to_value(error).unwrap_or_else(|e| {
134            JsonValue::String(format!("Failed to serialize error. Details: '{e}'"))
135        });
136
137        Self {
138            message,
139            error_code,
140            details,
141        }
142    }
143}