use std::fmt;
use http::StatusCode;
use crate::response::{IntoResponse, Response};
pub type Result<T = Response, E = Error> = std::result::Result<T, E>;
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub struct Error {
status: StatusCode,
message: String,
source: Option<BoxError>,
}
impl Error {
pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
Self {
status,
message: message.into(),
source: None,
}
}
pub fn with_source(
status: StatusCode,
message: impl Into<String>,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
Self {
status,
message: message.into(),
source: Some(Box::new(source)),
}
}
pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
self.source.as_deref()?.downcast_ref::<E>()
}
pub fn not_found() -> Self {
Self::new(StatusCode::NOT_FOUND, "Not Found")
}
pub fn forbidden() -> Self {
Self::new(StatusCode::FORBIDDEN, "Forbidden")
}
pub fn bad_request(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, message)
}
pub fn unprocessable(message: impl Into<String>) -> Self {
Self::new(StatusCode::UNPROCESSABLE_ENTITY, message)
}
pub fn internal(message: impl Into<String>) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn message(&self) -> &str {
&self.message
}
pub fn source(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
self.source.as_deref()
}
}
impl<E> From<E> for Error
where
E: std::error::Error + Send + Sync + 'static,
{
fn from(err: E) -> Self {
Self {
status: StatusCode::INTERNAL_SERVER_ERROR,
message: err.to_string(),
source: Some(Box::new(err)),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
return f
.debug_struct("Error")
.field("status", &self.status)
.field("message", &self.message)
.field("source", &self.source)
.finish();
}
write!(f, "{}", self.message)?;
let mut source = self.source.as_deref().and_then(|err| err.source());
if source.is_some() {
write!(f, "\n\nCaused by:")?;
}
while let Some(err) = source {
write!(f, "\n {err}")?;
source = err.source();
}
Ok(())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.status, self.message)
}
}
#[derive(Debug, Clone)]
pub struct ErrorReport {
pub status: StatusCode,
pub message: String,
pub causes: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Bare;
impl IntoResponse for Error {
fn into_response(self) -> Response {
if self.status.is_server_error() {
let mut causes = Vec::new();
let mut source = self.source.as_deref().and_then(|err| err.source());
while let Some(err) = source {
causes.push(err.to_string());
source = err.source();
}
tracing::event!(
target: "glacier",
tracing::Level::ERROR,
http.response.status_code = i64::from(self.status.as_u16()),
error.message = %self.message,
error.causes = ?causes,
"request failed: {}",
self.message
);
let reason = self.status.canonical_reason().unwrap_or("Error");
let mut res = Response::text(reason).with_status(self.status);
res.extensions_mut().insert(Bare);
res.extensions_mut().insert(ErrorReport {
status: self.status,
message: self.message,
causes,
});
res
} else {
let bare = Some(self.message.as_str()) == self.status.canonical_reason();
let mut res = Response::text(self.message).with_status(self.status);
if bare {
res.extensions_mut().insert(Bare);
}
res
}
}
}