use std::fmt;
use lambda_http::http::{HeaderName, HeaderValue, StatusCode};
pub const INTERNAL_MESSAGE: &str = "InternalServerError";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FailureKind {
Admission,
Decode,
Policy,
Handler,
Serialization,
Deadline,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Failure {
status: StatusCode,
code: &'static str,
message: String,
detail: Option<String>,
kind: FailureKind,
headers: Vec<(HeaderName, HeaderValue)>,
}
impl Failure {
#[must_use]
pub fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
Self {
status,
code,
message: message.into(),
detail: None,
kind: FailureKind::Handler,
headers: Vec::new(),
}
}
#[must_use]
pub fn internal(code: &'static str, detail: impl Into<String>) -> Self {
Self {
status: StatusCode::INTERNAL_SERVER_ERROR,
code,
message: INTERNAL_MESSAGE.to_owned(),
detail: Some(detail.into()),
kind: FailureKind::Handler,
headers: Vec::new(),
}
}
#[must_use]
pub fn from_error(code: &'static str, error: &dyn std::error::Error) -> Self {
Self::internal(code, crate::error::chain(error))
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into());
self
}
#[must_use]
pub fn with_kind(mut self, kind: FailureKind) -> Self {
self.kind = kind;
self
}
#[must_use]
pub fn with_header(mut self, name: &str, value: &str) -> Self {
if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
self.headers.push((name, value));
}
self
}
#[must_use]
pub fn with_headers<I, K, V>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
for (name, value) in headers {
self = self.with_header(name.as_ref(), value.as_ref());
}
self
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn code(&self) -> &'static str {
self.code
}
pub fn kind(&self) -> FailureKind {
self.kind
}
pub fn headers(&self) -> &[(HeaderName, HeaderValue)] {
&self.headers
}
pub fn public_message(&self) -> &str {
if self.status.is_server_error() {
INTERNAL_MESSAGE
} else {
&self.message
}
}
pub fn internal_detail(&self) -> String {
match (&self.detail, self.message.as_str()) {
(Some(detail), message) if message != INTERNAL_MESSAGE && !message.is_empty() => {
format!("{message}: {detail}")
}
(Some(detail), _) => detail.clone(),
(None, message) => message.to_owned(),
}
}
pub fn is_server_error(&self) -> bool {
self.status.is_server_error()
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.status.as_u16(), self.public_message())
}
}
impl std::error::Error for Failure {}
impl From<crate::RuntimeError> for Failure {
fn from(error: crate::RuntimeError) -> Self {
let code = match error {
crate::RuntimeError::DeadlineExceeded { .. } => super::codes::TIMEOUT,
crate::RuntimeError::LimitExceeded { .. } => super::codes::LIMIT_EXCEEDED,
_ => super::codes::UNHANDLED,
};
let kind = match error {
crate::RuntimeError::DeadlineExceeded { .. } => FailureKind::Deadline,
_ => FailureKind::Handler,
};
Self::from_error(code, &error).with_kind(kind)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorDefinition {
pub code: &'static str,
pub status: StatusCode,
pub message: &'static str,
}
impl ErrorDefinition {
pub const fn new(code: &'static str, status: StatusCode, message: &'static str) -> Self {
Self {
code,
status,
message,
}
}
pub fn failure(&self) -> Failure {
Failure::new(self.status, self.code, self.message)
}
}
pub trait ErrorCatalog {
fn definition(&self, code: &str) -> Option<ErrorDefinition>;
fn failure(&self, code: &'static str) -> Failure {
self.definition(code).map_or_else(
|| {
Failure::internal(
super::codes::UNHANDLED,
format!("unknown error code {code}"),
)
},
|definition| definition.failure(),
)
}
}
impl ErrorCatalog for &[ErrorDefinition] {
fn definition(&self, code: &str) -> Option<ErrorDefinition> {
self.iter().find(|entry| entry.code == code).copied()
}
}