use actix_web::http::StatusCode;
use actix_web::ResponseError;
use log::{error, info};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::{borrow::Cow, error::Error as StdError};
use utoipa::ToSchema;
pub const MAX_REPORTED_PARSE_ERRORS: usize = 1_000;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct ErrorResponse {
#[schema(example = "Unknown input format 'xml'.")]
pub message: String,
#[schema(example = "UnknownInputFormat")]
pub error_code: Cow<'static, str>,
#[schema(value_type=Object)]
pub details: JsonValue,
}
pub trait DetailedError: StdError + ResponseError + Serialize {
fn error_code(&self) -> Cow<'static, str>;
}
impl<E> From<&E> for ErrorResponse
where
E: DetailedError,
{
fn from(error: &E) -> ErrorResponse {
Self::from_error(error)
}
}
impl ErrorResponse {
pub fn from_error<E>(error: &E) -> Self
where
E: DetailedError,
{
let response = Self::from_error_nolog(error);
if error.status_code().is_success() {
error!(
"[HTTP error (caused by implementation)] expected error but got success status code {} {}: {}",
error.status_code(),
response.error_code,
response.message
);
} else if error.status_code().is_client_error() {
info!(
"[HTTP error (caused by client)] {} {}: {}",
error.status_code(),
response.error_code,
response.message
);
} else {
error!(
"[HTTP error (caused by implementation)] {} {}: {}",
error.status_code(),
response.error_code,
response.message
);
}
if error.status_code() == StatusCode::INTERNAL_SERVER_ERROR {
if let Some(backtrace) = response
.details
.get("backtrace")
.and_then(JsonValue::as_str)
{
error!("Error backtrace:\n{backtrace}");
}
}
response
}
pub fn from_error_nolog<E>(error: &E) -> Self
where
E: DetailedError,
{
let message = error.to_string();
let error_code = error.error_code();
let details = serde_json::to_value(error).unwrap_or_else(|e| {
JsonValue::String(format!("Failed to serialize error. Details: '{e}'"))
});
Self {
message,
error_code,
details,
}
}
}