1use crate::secret_redaction::secret_redactor;
2use actix_web::ResponseError;
3use actix_web::http::StatusCode;
4use log::{error, info};
5use serde::{Deserialize, Serialize};
6use serde_json::Value as JsonValue;
7use std::{borrow::Cow, error::Error as StdError};
8use tracing::Level;
9use utoipa::ToSchema;
10pub const MAX_REPORTED_PARSE_ERRORS: usize = 1_000;
11
12#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
14pub struct ErrorResponse {
15 #[schema(example = "Explanation of the error that occurred.")]
17 pub message: String,
18 #[schema(example = "CodeSpecifyingErrorType")]
20 pub error_code: Cow<'static, str>,
21 #[schema(value_type = Value)]
24 pub details: JsonValue,
25}
26
27pub trait DetailedError: StdError + Serialize {
33 fn error_code(&self) -> Cow<'static, str>;
35
36 fn log_level(&self) -> Level {
38 Level::ERROR
39 }
40}
41
42pub trait EngineError: StdError + erased_serde::Serialize + Send + Sync + 'static {
46 fn error_code(&self) -> Cow<'static, str>;
48
49 fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
51 None
52 }
53}
54
55erased_serde::serialize_trait_object!(EngineError);
56
57impl<E> From<&E> for ErrorResponse
58where
59 E: DetailedError + ResponseError,
60{
61 fn from(error: &E) -> ErrorResponse {
67 Self::from_error(error)
68 }
69}
70
71impl ErrorResponse {
72 pub fn from_error<E>(error: &E) -> Self
73 where
74 E: DetailedError + ResponseError,
75 {
76 let response = Self::from_error_nolog(error);
78
79 if error.status_code().is_success() {
81 error!(
83 "[HTTP error (caused by implementation)] expected error but got success status code {} {}: {}",
84 error.status_code(),
85 response.error_code,
86 response.message
87 );
88 } else if error.status_code().is_client_error() {
89 info!(
91 "[HTTP error (caused by client)] {} {}: {}",
92 error.status_code(),
93 response.error_code,
94 response.message
95 );
96 } else if error.status_code() == StatusCode::SERVICE_UNAVAILABLE {
97 info!(
98 "[HTTP error] {} {}: {}",
99 error.status_code(),
100 response.error_code,
101 response.message
102 );
103 } else {
104 error!(
108 "[HTTP error (caused by implementation)] {} {}: {}",
109 error.status_code(),
110 response.error_code,
111 response.message
112 );
113 }
114
115 if error.status_code() == StatusCode::INTERNAL_SERVER_ERROR
117 && let Some(backtrace) = response
118 .details
119 .get("backtrace")
120 .and_then(JsonValue::as_str)
121 {
122 error!("Error backtrace:\n{backtrace}");
123 }
124
125 response
126 }
127
128 pub fn from_error_nolog<E>(error: &E) -> Self
129 where
130 E: DetailedError,
131 {
132 let redactor = secret_redactor();
134 let message = redactor.redact(&error.to_string()).into_owned();
135 let error_code = error.error_code();
136 let mut details = serde_json::to_value(error).unwrap_or_else(|e| {
137 JsonValue::String(format!("Failed to serialize error. Details: '{e}'"))
138 });
139 redactor.redact_json(&mut details);
140
141 Self {
142 message,
143 error_code,
144 details,
145 }
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::{DetailedError, ErrorResponse};
152 use crate::secret_redaction::secret_redactor;
153 use serde::Serialize;
154 use serde_json::json;
155 use std::borrow::Cow;
156 use thiserror::Error as ThisError;
157
158 #[derive(Debug, Serialize, ThisError)]
159 #[error("connection to {uri} refused")]
160 struct ConnectError {
161 uri: String,
162 }
163
164 impl DetailedError for ConnectError {
165 fn error_code(&self) -> Cow<'static, str> {
166 Cow::from("ConnectError")
167 }
168 }
169
170 #[test]
173 fn response_shows_the_secret_reference_not_the_value() {
174 let uri = "postgres://feldera:response-test-secret@db:5432/app";
175 secret_redactor().register("${secret:kubernetes:pg/uri}", uri);
176
177 let response = ErrorResponse::from_error_nolog(&ConnectError {
178 uri: uri.to_string(),
179 });
180
181 assert_eq!(
182 response.message,
183 "connection to ${secret:kubernetes:pg/uri} refused"
184 );
185 assert_eq!(
186 response.details,
187 json!({"uri": "${secret:kubernetes:pg/uri}"})
188 );
189 }
190}