use std::any::Any;
use std::collections::BTreeMap;
use std::error::Error as StdError;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use http::header::{CONTENT_TYPE, HeaderName, HeaderValue, RETRY_AFTER, X_CONTENT_TYPE_OPTIONS};
use http::{HeaderMap, StatusCode};
use navree_kernel::__private::is_app_module;
use navree_kernel::{AppContext, BoxError};
use serde::Serialize;
use crate::body::Body;
use crate::codes;
use crate::options::ErrorOptions;
use crate::response::{IntoResponse, Response};
pub const ERROR_CONTENT_TYPE: &str = "application/json";
const INTERNAL_MESSAGE: &str = "Internal server error";
pub type Result<T, E = AppError> = std::result::Result<T, E>;
pub struct AppError {
pub status: StatusCode,
pub code: String,
pub title: String,
pub detail: Option<String>,
pub errors: Option<Box<BTreeMap<String, Vec<String>>>>,
pub headers: Box<HeaderMap>,
pub source: Option<BoxError>,
}
impl AppError {
pub fn new(status: StatusCode, code: impl Into<String>, title: impl Into<String>) -> Self {
Self {
status,
code: code.into(),
title: title.into(),
detail: None,
errors: None,
headers: Box::default(),
source: None,
}
}
pub fn from_status(status: StatusCode) -> Self {
let reason = status.canonical_reason().unwrap_or("Error");
match status.as_u16() {
401 => Self::new(status, codes::UNAUTHENTICATED, reason),
500 => Self::new(status, codes::INTERNAL_ERROR, INTERNAL_MESSAGE),
_ => Self::new(status, slug(reason), reason),
}
}
pub fn bad_request(detail: impl Into<String>) -> Self {
Self::from_status(StatusCode::BAD_REQUEST).with_detail(detail)
}
pub fn invalid_filter(detail: impl Into<String>) -> Self {
Self::bad_request(detail).with_code(codes::INVALID_FILTER)
}
pub fn unauthenticated() -> Self {
Self::from_status(StatusCode::UNAUTHORIZED)
}
pub fn two_factor_required() -> Self {
Self::unauthenticated()
.with_code(codes::TWO_FACTOR_REQUIRED)
.with_detail("Two-factor authentication required")
}
pub fn forbidden() -> Self {
Self::from_status(StatusCode::FORBIDDEN)
}
pub fn not_found() -> Self {
Self::from_status(StatusCode::NOT_FOUND)
}
pub fn conflict(detail: impl Into<String>) -> Self {
Self::from_status(StatusCode::CONFLICT).with_detail(detail)
}
pub fn limit_reached(detail: impl Into<String>) -> Self {
Self::conflict(detail).with_code(codes::LIMIT_REACHED)
}
pub fn demo_read_only() -> Self {
Self::forbidden()
.with_code(codes::DEMO_READ_ONLY)
.with_detail("Demo workspaces are read-only.")
}
pub fn csrf_mismatch() -> Self {
Self::new(
StatusCode::FORBIDDEN,
codes::CSRF_TOKEN_MISMATCH,
"Invalid CSRF token",
)
}
pub fn page_expired() -> Self {
Self::new(
StatusCode::from_u16(419).unwrap_or(StatusCode::BAD_REQUEST),
codes::PAGE_EXPIRED,
"Page Expired",
)
}
pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self {
let mut error = Self::new(
StatusCode::BAD_REQUEST,
codes::VALIDATION_FAILED,
"Bad Request",
);
error.errors = Some(Box::new(errors));
error
}
pub fn payload_too_large(limit: usize) -> Self {
Self::from_status(StatusCode::PAYLOAD_TOO_LARGE)
.with_detail(format!("The request body must not exceed {limit} bytes."))
}
pub fn too_many_requests(retry_after: Duration) -> Self {
let secs = retry_after_secs(retry_after);
Self::from_status(StatusCode::TOO_MANY_REQUESTS)
.with_header(RETRY_AFTER, HeaderValue::from(secs))
}
pub fn service_unavailable(detail: impl Into<String>) -> Self {
Self::from_status(StatusCode::SERVICE_UNAVAILABLE).with_detail(detail)
}
pub fn internal(err: impl Into<BoxError>) -> Self {
let mut error = Self::from_status(StatusCode::INTERNAL_SERVER_ERROR);
error.source = Some(err.into());
error
}
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn with_code(mut self, code: impl Into<String>) -> Self {
self.code = code.into();
self
}
pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.headers.insert(name, value);
self
}
pub fn with_source(mut self, source: impl Into<BoxError>) -> Self {
self.source = Some(source.into());
self
}
pub fn body(&self) -> serde_json::Value {
self.body_as(ErrorFormat::default())
}
pub(crate) fn body_as(&self, format: ErrorFormat) -> serde_json::Value {
serde_json::to_value(self.wire(format)).unwrap_or_default()
}
fn wire(&self, format: ErrorFormat) -> ErrorBody<'_> {
let errors = self.errors.as_deref();
let message = match errors {
Some(errors) if !errors.is_empty() => {
Message::Many(errors.values().flatten().map(String::as_str).collect())
}
_ => Message::One(self.detail.as_deref().unwrap_or(&self.title)),
};
let code = (format.code && !self.code.is_empty()).then_some(self.code.as_str());
ErrorBody {
status_code: self.status.as_u16(),
message,
error: self.status.canonical_reason().unwrap_or(&self.title),
code,
errors,
}
}
pub fn take_from(response: &mut Response) -> Option<AppError> {
response
.extensions_mut()
.remove::<PendingError>()
.and_then(|pending| pending.take())
}
pub(crate) fn render(&self, format: ErrorFormat) -> Response {
let body = serde_json::to_vec(&self.wire(format)).unwrap_or_default();
let mut response = Response::new(Body::from(body));
*response.status_mut() = self.status;
let headers = response.headers_mut();
for (name, value) in self.headers.iter() {
headers.insert(name, value.clone());
}
headers.insert(CONTENT_TYPE, HeaderValue::from_static(ERROR_CONTENT_TYPE));
headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
response
}
pub(crate) fn rejection(status: StatusCode, text: impl Into<String>) -> Self {
let status = if status == StatusCode::UNPROCESSABLE_ENTITY {
StatusCode::BAD_REQUEST
} else {
status
};
let error = Self::from_status(status);
let text = text.into();
let text = text.trim();
if text.is_empty() {
error
} else if status.is_client_error() {
error.with_detail(text)
} else {
error.with_source(text.to_owned())
}
}
pub(crate) fn log_chain(&self) -> String {
let mut out = format!("{} {}", self.status.as_u16(), self.title);
if let Some(detail) = &self.detail {
out.push_str(": ");
out.push_str(detail);
}
let mut next: Option<&(dyn StdError + 'static)> = self
.source
.as_deref()
.map(|e| e as &(dyn StdError + 'static));
while let Some(error) = next {
out.push_str(": ");
out.push_str(&error.to_string());
next = error.source();
}
out
}
}
pub(crate) fn retry_after_secs(d: Duration) -> u64 {
let secs = d.as_secs() + u64::from(d.subsec_nanos() > 0);
secs.max(1)
}
fn slug(title: &str) -> String {
title
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect()
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct ErrorFormat {
pub(crate) code: bool,
}
impl Default for ErrorFormat {
fn default() -> Self {
Self { code: true }
}
}
impl From<&ErrorOptions> for ErrorFormat {
fn from(options: &ErrorOptions) -> Self {
Self { code: options.code }
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ErrorBody<'a> {
status_code: u16,
message: Message<'a>,
error: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
code: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
errors: Option<&'a BTreeMap<String, Vec<String>>>,
}
#[derive(Serialize)]
#[serde(untagged)]
enum Message<'a> {
One(&'a str),
Many(Vec<&'a str>),
}
impl fmt::Debug for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AppError")
.field("status", &self.status)
.field("code", &self.code)
.field("title", &self.title)
.field("detail", &self.detail)
.field("errors", &self.errors)
.field("source", &self.source)
.finish_non_exhaustive()
}
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.status.as_u16(), self.title)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
impl<E: Into<BoxError>> From<E> for AppError {
fn from(error: E) -> Self {
Self::internal(error)
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let mut response = self.render(ErrorFormat::default());
response
.extensions_mut()
.insert(PendingError(Arc::new(Mutex::new(Some(self)))));
response
}
}
#[derive(Clone)]
pub(crate) struct PendingError(Arc<Mutex<Option<AppError>>>);
impl PendingError {
pub(crate) fn take(&self) -> Option<AppError> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).take()
}
}
#[derive(Clone)]
pub struct ErrorMapper {
type_name: &'static str,
map: Arc<MapFn>,
map_any: Arc<MapAnyFn>,
}
type MapFn = dyn Fn(&(dyn StdError + 'static)) -> Option<AppError> + Send + Sync;
type MapAnyFn = dyn Fn(&(dyn Any + Send + Sync)) -> Option<AppError> + Send + Sync;
impl ErrorMapper {
pub fn new<E: StdError + 'static>(f: fn(&E) -> Option<AppError>) -> Self {
Self {
type_name: std::any::type_name::<E>(),
map: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
map_any: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
}
}
pub fn apply(mappers: &[ErrorMapper], error: &AppError) -> Option<AppError> {
error
.source
.as_deref()
.and_then(|source| Self::apply_to(mappers, source))
}
pub fn apply_to(mappers: &[ErrorMapper], error: &(dyn StdError + 'static)) -> Option<AppError> {
let mut next = Some(error);
while let Some(cause) = next {
for mapper in mappers {
if let Some(mapped) = (mapper.map)(cause) {
return Some(mapped);
}
}
next = cause.source();
}
None
}
pub fn apply_any(mappers: &[ErrorMapper], error: &(dyn Any + Send + Sync)) -> Option<AppError> {
mappers.iter().find_map(|mapper| (mapper.map_any)(error))
}
}
impl fmt::Debug for ErrorMapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ErrorMapper")
.field("error_type", &self.type_name)
.finish()
}
}
pub fn mappers_of_plugins(ctx: &AppContext) -> Vec<String> {
let contributed = ctx.contributions::<ErrorMapper>();
if contributed
.iter()
.all(|mapper| is_app_module(ctx, mapper.module.id))
{
return Vec::new();
}
let plugins = ctx.plugins().plugins;
contributed
.iter()
.filter_map(|mapper| {
let module = mapper.module.id;
let plugin = plugins.iter().find(|plugin| {
!plugin.first_party && plugin.modules.iter().any(|member| member.id == module)
})?;
let error = mapper.value.type_name;
let outer = error.split_once('<').map_or(error, |(outer, _)| outer);
let own = outer
.strip_prefix(plugin.info.crate_name)
.is_some_and(|rest| rest.starts_with("::"));
if own {
return None;
}
Some(format!(
"plugin `{}` answers the app's errors of type `{error}` (m.map_error in `{}`), a type of another crate; only a module of the app maps another crate's errors: remove the plugin or update it to a version that maps only its own errors, and to use the plugin's mapping, register it from a module of the app (m.map_error)",
plugin.info.name, mapper.module.name
))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn app_error_stays_small_enough_for_result() {
assert!(
std::mem::size_of::<AppError>() < 128,
"AppError is {} bytes",
std::mem::size_of::<AppError>()
);
}
#[derive(Debug)]
struct Taken;
impl fmt::Display for Taken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("taken")
}
}
impl StdError for Taken {}
#[derive(Debug)]
struct Wrapped(Taken);
impl fmt::Display for Wrapped {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("wrapped")
}
}
impl StdError for Wrapped {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.0)
}
}
fn mappers() -> Vec<ErrorMapper> {
vec![ErrorMapper::new::<Taken>(|_| {
Some(AppError::conflict("already taken"))
})]
}
#[test]
fn mappers_apply_to_a_source_chain() {
let mappers = mappers();
let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Wrapped(Taken))).unwrap();
assert_eq!(mapped.status, StatusCode::CONFLICT);
let mapped = ErrorMapper::apply_to(&mappers, &Wrapped(Taken)).unwrap();
assert_eq!(mapped.detail.as_deref(), Some("already taken"));
assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
assert!(ErrorMapper::apply(&mappers, &AppError::not_found()).is_none());
}
#[test]
fn mappers_apply_to_errors_held_as_any() {
let mappers = mappers();
let held: Arc<dyn Any + Send + Sync> = Arc::new(Taken);
let mapped = ErrorMapper::apply_any(&mappers, &*held).unwrap();
assert_eq!(mapped.status, StatusCode::CONFLICT);
let other: Arc<dyn Any + Send + Sync> = Arc::new(Wrapped(Taken));
assert!(ErrorMapper::apply_any(&mappers, &*other).is_none());
}
#[test]
fn framework_errors_render_their_stable_codes() {
use serde_json::json;
let errors = BTreeMap::from([(
"email".to_owned(),
vec!["email must be a valid email address".to_owned()],
)]);
let cases = [
(
AppError::bad_request("The export is empty."),
json!({"statusCode": 400, "message": "The export is empty.", "error": "Bad Request", "code": "bad_request"}),
),
(
AppError::validation(errors.clone()),
json!({
"statusCode": 400,
"message": ["email must be a valid email address"],
"error": "Bad Request",
"code": "validation_failed",
"errors": {"email": ["email must be a valid email address"]},
}),
),
(
AppError::invalid_filter("Unknown filter `colour`."),
json!({"statusCode": 400, "message": "Unknown filter `colour`.", "error": "Bad Request", "code": "invalid_filter"}),
),
(
AppError::unauthenticated(),
json!({"statusCode": 401, "message": "Unauthorized", "error": "Unauthorized", "code": "unauthenticated"}),
),
(
AppError::two_factor_required(),
json!({"statusCode": 401, "message": "Two-factor authentication required", "error": "Unauthorized", "code": "two_factor_required"}),
),
(
AppError::forbidden(),
json!({"statusCode": 403, "message": "Forbidden", "error": "Forbidden", "code": "forbidden"}),
),
(
AppError::csrf_mismatch(),
json!({"statusCode": 403, "message": "Invalid CSRF token", "error": "Forbidden", "code": "csrf_token_mismatch"}),
),
(
AppError::demo_read_only(),
json!({"statusCode": 403, "message": "Demo workspaces are read-only.", "error": "Forbidden", "code": "demo_read_only"}),
),
(
AppError::not_found(),
json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"}),
),
(
AppError::conflict("Email taken"),
json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"}),
),
(
AppError::limit_reached("Your plan includes 5 seats."),
json!({"statusCode": 409, "message": "Your plan includes 5 seats.", "error": "Conflict", "code": "limit_reached"}),
),
(
AppError::payload_too_large(16),
json!({"statusCode": 413, "message": "The request body must not exceed 16 bytes.", "error": "Payload Too Large", "code": "payload_too_large"}),
),
(
AppError::page_expired(),
json!({"statusCode": 419, "message": "Page Expired", "error": "Page Expired", "code": "page_expired"}),
),
(
AppError::too_many_requests(Duration::from_secs(3)),
json!({"statusCode": 429, "message": "Too Many Requests", "error": "Too Many Requests", "code": "too_many_requests"}),
),
(
AppError::internal("db password=hunter2"),
json!({"statusCode": 500, "message": "Internal server error", "error": "Internal Server Error", "code": "internal_error"}),
),
(
AppError::service_unavailable("Try again later."),
json!({"statusCode": 503, "message": "Try again later.", "error": "Service Unavailable", "code": "service_unavailable"}),
),
];
for (error, body) in cases {
assert!(
codes::ALL.contains(&error.code.as_str()),
"`{}` is in the table of stable codes",
error.code
);
assert_eq!(error.body(), body, "{error}");
}
}
#[test]
fn statuses_without_a_constructor_derive_their_code() {
let cases = [
(StatusCode::METHOD_NOT_ALLOWED, codes::METHOD_NOT_ALLOWED),
(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
codes::UNSUPPORTED_MEDIA_TYPE,
),
(StatusCode::PAYMENT_REQUIRED, "payment_required"),
(StatusCode::GONE, "gone"),
];
for (status, code) in cases {
assert_eq!(AppError::from_status(status).code, code, "{status}");
}
}
#[test]
fn with_code_sets_the_rendered_code() {
let error = AppError::conflict("The campaign is already running.")
.with_code("campaign_already_running");
assert_eq!(error.status, StatusCode::CONFLICT);
assert_eq!(error.code, "campaign_already_running");
assert_eq!(
error.body(),
serde_json::json!({
"statusCode": 409,
"message": "The campaign is already running.",
"error": "Conflict",
"code": "campaign_already_running",
})
);
}
#[test]
fn code_comes_after_error_and_before_errors() {
let errors = BTreeMap::from([("name".to_owned(), vec!["name is required".to_owned()])]);
let response = AppError::validation(errors).render(ErrorFormat::default());
let text = futures_util::FutureExt::now_or_never(http_body_util::BodyExt::collect(
response.into_body(),
))
.expect("a full body")
.expect("collects")
.to_bytes();
let text = String::from_utf8_lossy(&text);
let positions: Vec<usize> = [
"\"statusCode\"",
"\"message\"",
"\"error\"",
"\"code\"",
"\"errors\"",
]
.iter()
.map(|key| text.find(key).expect(key))
.collect();
assert!(positions.is_sorted(), "member order: {text}");
}
#[test]
fn the_code_is_left_out_when_turned_off_or_empty() {
let off = ErrorFormat { code: false };
let body = AppError::not_found().body_as(off);
assert_eq!(
body,
serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found"})
);
let empty = AppError::new(StatusCode::IM_A_TEAPOT, "", "Short and stout");
assert!(empty.body().get("code").is_none(), "{}", empty.body());
}
#[test]
fn statuses_have_codes_and_titles() {
assert_eq!(AppError::unauthenticated().status, StatusCode::UNAUTHORIZED);
assert_eq!(AppError::unauthenticated().title, "Unauthorized");
assert_eq!(AppError::forbidden().code, "forbidden");
assert_eq!(AppError::forbidden().title, "Forbidden");
assert_eq!(
AppError::from_status(StatusCode::TOO_MANY_REQUESTS).title,
"Too Many Requests"
);
let teapot = AppError::from_status(StatusCode::IM_A_TEAPOT);
assert_eq!(teapot.code, "i_m_a_teapot");
assert_eq!(teapot.title, "I'm a teapot");
}
#[test]
fn csrf_mismatch_is_403_invalid_csrf_token() {
let error = AppError::csrf_mismatch();
assert_eq!(error.status, StatusCode::FORBIDDEN);
assert_eq!(error.code, "csrf_token_mismatch");
assert_eq!(
error.body(),
serde_json::json!({
"statusCode": 403,
"message": "Invalid CSRF token",
"error": "Forbidden",
"code": "csrf_token_mismatch",
})
);
}
#[test]
fn body_uses_detail_as_message_and_reason_phrase_as_error() {
assert_eq!(
AppError::not_found().body(),
serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"})
);
assert_eq!(
AppError::conflict("Email taken").body(),
serde_json::json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"})
);
let custom = AppError::new(
StatusCode::UNAUTHORIZED,
"invalid_signature",
"Invalid signature.",
);
assert_eq!(
custom.body(),
serde_json::json!({
"statusCode": 401,
"message": "Invalid signature.",
"error": "Unauthorized",
"code": "invalid_signature",
})
);
let odd = AppError::from_status(StatusCode::from_u16(599).unwrap());
assert_eq!(odd.body()["error"], "Error", "no reason phrase");
}
#[test]
fn validation_is_400_with_flattened_messages_in_field_order() {
let errors = BTreeMap::from([
(
"name".to_owned(),
vec!["name should not be empty".to_owned()],
),
(
"email".to_owned(),
vec![
"email must be a valid email address".to_owned(),
"email must be shorter than or equal to 255 characters".to_owned(),
],
),
]);
let error = AppError::validation(errors.clone()).with_detail("ignored when rendering");
assert_eq!(error.status, StatusCode::BAD_REQUEST);
assert_eq!(error.code, "validation_failed");
assert_eq!(
error.body(),
serde_json::json!({
"statusCode": 400,
"message": [
"email must be a valid email address",
"email must be shorter than or equal to 255 characters",
"name should not be empty",
],
"error": "Bad Request",
"code": "validation_failed",
"errors": errors,
})
);
let empty = AppError::validation(BTreeMap::new());
assert_eq!(empty.body()["message"], "Bad Request");
assert_eq!(empty.body()["errors"], serde_json::json!({}));
}
#[test]
fn rendered_errors_are_application_json() {
let response = AppError::not_found().render(ErrorFormat::default());
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(response.headers()[CONTENT_TYPE], ERROR_CONTENT_TYPE);
assert_eq!(ERROR_CONTENT_TYPE, "application/json");
}
#[test]
fn too_many_requests_rounds_retry_after_up() {
let error = AppError::too_many_requests(Duration::from_millis(1500));
assert_eq!(error.headers[RETRY_AFTER], "2");
let error = AppError::too_many_requests(Duration::ZERO);
assert_eq!(error.headers[RETRY_AFTER], "1");
}
#[test]
fn internal_keeps_source_but_renders_no_detail() {
let error = AppError::internal(std::io::Error::other("db password=hunter2"));
assert_eq!(
error.body(),
serde_json::json!({
"statusCode": 500,
"message": "Internal server error",
"error": "Internal Server Error",
"code": "internal_error",
})
);
assert!(error.log_chain().contains("hunter2"), "logged, not sent");
}
#[test]
fn take_from_returns_the_error_a_response_carries_once() {
let mut response = AppError::conflict("Taken").into_response();
let error = AppError::take_from(&mut response).expect("the pending error");
assert_eq!(error.status, StatusCode::CONFLICT);
assert_eq!(error.detail.as_deref(), Some("Taken"));
assert!(AppError::take_from(&mut response).is_none(), "taken once");
let mut plain = (StatusCode::OK, "fine").into_response();
assert!(AppError::take_from(&mut plain).is_none());
}
#[test]
fn mappers_apply_to_the_source_chain() {
#[derive(Debug)]
struct Missing;
impl fmt::Display for Missing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("missing")
}
}
impl StdError for Missing {}
let mappers = [ErrorMapper::new::<Missing>(|_| Some(AppError::not_found()))];
let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Missing)).expect("mapped");
assert_eq!(mapped.status, StatusCode::NOT_FOUND);
assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
assert!(ErrorMapper::apply(&[], &AppError::internal(Missing)).is_none());
}
#[test]
fn strings_convert_with_question_mark() {
fn fails() -> Result<()> {
Err("boom")?
}
let error = fails().unwrap_err();
assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(error.source.unwrap().to_string(), "boom");
}
}