use lambda_http::http::{StatusCode, header};
use lambda_http::{Body, Response};
use super::failure::Failure;
use super::response::{HttpResponse, apply_headers};
pub trait ErrorRenderer: Send + Sync + 'static {
fn render(&self, failure: &Failure) -> HttpResponse;
}
pub fn literal(status: StatusCode, content_type: &'static str, body: String) -> HttpResponse {
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, content_type)
.body(Body::Text(body))
.unwrap_or_else(|_| {
let mut response = Response::new(Body::Empty);
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
response
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PlainErrors;
impl ErrorRenderer for PlainErrors {
fn render(&self, failure: &Failure) -> HttpResponse {
let body = serde_json::json!({
"errorCode": failure.code(),
"errorMessage": failure.public_message(),
})
.to_string();
let mut response = literal(failure.status(), "application/json", body);
apply_headers(&mut response, failure.headers());
response
}
}
#[cfg(feature = "problem")]
mod problem {
use super::{ErrorRenderer, Failure, HttpResponse, apply_headers, literal};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProblemErrors {
type_base: Option<String>,
}
impl ProblemErrors {
#[must_use]
pub fn with_type_base(mut self, base: impl Into<String>) -> Self {
self.type_base = Some(base.into());
self
}
}
impl ErrorRenderer for ProblemErrors {
fn render(&self, failure: &Failure) -> HttpResponse {
let mut details = problem_details::ProblemDetails::from_status_code(failure.status())
.with_detail(failure.public_message());
if let Some(base) = &self.type_base
&& let Ok(uri) =
format!("{base}{}", failure.code()).parse::<lambda_http::http::Uri>()
{
details = details.with_type(uri);
}
let body = serde_json::to_string(&details)
.unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
let mut response = literal(failure.status(), "application/problem+json", body);
apply_headers(&mut response, failure.headers());
response
}
}
}
#[cfg(feature = "problem")]
pub use problem::ProblemErrors;