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#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
13pub struct ErrorResponse {
14 #[schema(example = "Explanation of the error that occurred.")]
16 pub message: String,
17 #[schema(example = "CodeSpecifyingErrorType")]
19 pub error_code: Cow<'static, str>,
20 #[schema(value_type = Value)]
23 pub details: JsonValue,
24}
25
26pub trait DetailedError: StdError + Serialize {
32 fn error_code(&self) -> Cow<'static, str>;
34
35 fn log_level(&self) -> Level {
37 Level::ERROR
38 }
39}
40
41pub trait EngineError: StdError + erased_serde::Serialize + Send + Sync + 'static {
45 fn error_code(&self) -> Cow<'static, str>;
47
48 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 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 let response = Self::from_error_nolog(error);
77
78 if error.status_code().is_success() {
80 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 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 error!(
107 "[HTTP error (caused by implementation)] {} {}: {}",
108 error.status_code(),
109 response.error_code,
110 response.message
111 );
112 }
113
114 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}