#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum ErrorLevel {
Debug,
Info,
Warning,
Error,
Critical,
}
#[non_exhaustive]
pub struct ErrorContext<'a> {
pub caption: &'a str,
pub kind: &'a str,
pub level: ErrorLevel,
pub is_fatal: bool,
pub is_retryable: bool,
}
impl<'a> ErrorContext<'a> {
pub fn new(
caption: &'a str,
kind: &'a str,
level: ErrorLevel,
is_fatal: bool,
is_retryable: bool,
) -> Self {
Self {
caption,
kind,
level,
is_fatal,
is_retryable,
}
}
}
use std::sync::OnceLock;
type ErrorHookFn = Box<dyn Fn(ErrorContext<'_>) + Send + Sync + 'static>;
static ERROR_HOOK: OnceLock<ErrorHookFn> = OnceLock::new();
#[doc(hidden)]
pub trait ErrorSource {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)>;
}
impl ErrorSource for std::io::Error {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self)
}
}
impl ErrorSource for Box<dyn std::error::Error + Send + Sync> {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.as_ref())
}
}
impl ErrorSource for Box<dyn std::error::Error> {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.as_ref())
}
}
impl ErrorSource for Option<std::io::Error> {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.as_ref()
.map(|error| error as &(dyn std::error::Error + 'static))
}
}
impl ErrorSource for Option<Box<dyn std::error::Error + Send + Sync>> {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.as_deref()
.map(|error| error as &(dyn std::error::Error + 'static))
}
}
impl ErrorSource for Option<Box<dyn std::error::Error>> {
fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.as_deref()
.map(|error| error as &(dyn std::error::Error + 'static))
}
}
#[deprecated(
since = "1.0.0",
note = "register_error_hook silently drops registration failures; use \
try_register_error_hook instead"
)]
pub fn register_error_hook<F>(callback: F)
where
F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
{
let _ = try_register_error_hook(callback);
}
pub fn try_register_error_hook<F>(callback: F) -> Result<(), &'static str>
where
F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
{
ERROR_HOOK
.set(Box::new(callback))
.map_err(|_| "Error hook already registered")
}
thread_local! {
static IN_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
struct InHookGuard;
impl Drop for InHookGuard {
fn drop(&mut self) {
IN_HOOK.with(|flag| flag.set(false));
}
}
#[doc(hidden)]
pub fn call_error_hook(caption: &str, kind: &str, is_fatal: bool, is_retryable: bool) {
let Some(hook) = ERROR_HOOK.get() else {
return;
};
if IN_HOOK.with(|flag| flag.replace(true)) {
return;
}
let _guard = InHookGuard;
let level = if is_fatal {
ErrorLevel::Critical
} else if !is_retryable {
ErrorLevel::Error
} else if kind == "Warning" {
ErrorLevel::Warning
} else if kind == "Debug" {
ErrorLevel::Debug
} else {
ErrorLevel::Info
};
let context = ErrorContext {
caption,
kind,
level,
is_fatal,
is_retryable,
};
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(context)));
if let Err(payload) = outcome {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(payload)));
}
}
#[macro_export]
macro_rules! define_errors {
(@emit [[$(#[$meta:meta])*] [$vis:vis] $name:ident]
$({
[$($vattr:tt)*]
[$($disp:tt)*]
[$kind:ident $(, $tag:ident = $val:expr)*]
$variant:ident $({ $($field:ident : $ftype:ty),* })?
})*
) => {
$(#[$meta])* #[derive(::core::fmt::Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize))]
$vis enum $name {
$( $($vattr)* $variant $( { $($field : $ftype),* } )?, )*
}
const _: () = {
$( $( $crate::define_errors!(@check_tag $tag); )* )*
};
impl $name {
$(
$crate::__private::pastey::paste! {
pub fn [<$variant:lower>]($($($field : $ftype),*)?) -> Self {
let instance = Self::$variant $( { $($field),* } )?;
$crate::macros::call_error_hook(
instance.caption(),
instance.kind(),
instance.is_fatal(),
instance.is_retryable()
);
instance
}
}
)*
pub fn caption(&self) -> &'static str {
match self {
$( Self::$variant { .. } => {
$crate::define_errors!(@get_caption $kind $(, $tag = $val)*)
} ),*
}
}
pub fn kind(&self) -> &'static str {
match self {
$( Self::$variant { .. } => {
::core::stringify!($kind)
} ),*
}
}
pub fn is_retryable(&self) -> bool {
match self {
$( Self::$variant { .. } => {
$crate::define_errors!(@get_tag retryable, false $(, $tag = $val)*)
} ),*
}
}
pub fn is_fatal(&self) -> bool {
match self {
$( Self::$variant { .. } => {
$crate::define_errors!(@get_tag fatal, false $(, $tag = $val)*)
} ),*
}
}
pub fn status_code(&self) -> u16 {
match self {
$( Self::$variant { .. } => {
$crate::define_errors!(@get_tag status, 500 $(, $tag = $val)*)
} ),*
}
}
pub fn exit_code(&self) -> i32 {
match self {
$( Self::$variant { .. } => {
$crate::define_errors!(@get_tag exit, 1 $(, $tag = $val)*)
} ),*
}
}
}
impl ::core::fmt::Display for $name {
#[allow(unused_variables)]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
match self {
$( Self::$variant $( { $($field),* } )? => {
$crate::define_errors!(
@display f [$($disp)*] self.caption(); $variant $($($field)*)?
)
} ),*
}
}
}
impl ::std::error::Error for $name {
#[allow(unused_variables)]
fn source(&self) -> ::core::option::Option<&(dyn ::std::error::Error + 'static)> {
match self {
$( Self::$variant $( { $($field),* } )? => {
$crate::define_errors!(@find_source $( $($field),* )? )
} ),*
}
}
}
};
(@display $f:ident [$display:literal $(, $param:ident)*] $caption:expr; $variant:ident $($field:ident)*) => {
::core::write!($f, $display $(, $param = $param)*)
};
(@display $f:ident [] $caption:expr; $variant:ident $($field:ident)*) => {{
::core::write!($f, "{}: ", $caption)?;
$f.write_str(::core::stringify!($variant))?;
$(
::core::write!($f, " | {} = ", ::core::stringify!($field))?;
$crate::define_errors!(@fmt_field $f, $field, $field)?;
)*
::core::result::Result::Ok(())
}};
(@display $($rest:tt)*) => {
::core::compile_error!(
"define_errors!: a variant may carry only one #[error(display = \"...\")] attribute"
)
};
(@fmt_field $f:ident, source, $field:ident) => {
::core::write!($f, "{}", $field)
};
(@fmt_field $f:ident, $name:ident, $field:ident) => {
::core::write!($f, "{:?}", $field)
};
(@check_tag caption) => {};
(@check_tag retryable) => {};
(@check_tag fatal) => {};
(@check_tag status) => {};
(@check_tag exit) => {};
(@check_tag $other:ident) => {
::core::compile_error!(::core::concat!(
"define_errors!: unknown #[kind] tag `",
::core::stringify!($other),
"`; expected one of `caption`, `retryable`, `fatal`, `status`, `exit`"
));
};
(@munch $hdr:tt [$($done:tt)*] [] [] []) => {
$crate::define_errors!(@emit $hdr $($done)*);
};
(@munch $hdr:tt $done:tt [$($attrs:tt)*] [] $kind:tt
#[error(display = $display:literal $(, $param:ident)* $(,)?)] $($rest:tt)*
) => {
$crate::define_errors!(@munch $hdr $done [$($attrs)*] [$display $(, $param)*] $kind $($rest)*);
};
(@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[error $($bad:tt)*] $($rest:tt)*) => {
::core::compile_error!(::core::concat!(
"define_errors!: expected a single `#[error(display = \"...\", field, ...)]` per variant, found `#[error",
::core::stringify!($($bad)*),
"]`"
));
};
(@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt []
#[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)] $($rest:tt)*
) => {
$crate::define_errors!(@munch $hdr $done [$($attrs)*] $disp [$kind $(, $tag = $val)*] $($rest)*);
};
(@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[kind $($bad:tt)*] $($rest:tt)*) => {
::core::compile_error!(::core::concat!(
"define_errors!: expected a single `#[kind(Name, tag = value, ...)]` per variant, found `#[kind",
::core::stringify!($($bad)*),
"]`"
));
};
(@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt $kind:tt #[$($attr:tt)*] $($rest:tt)*) => {
$crate::define_errors!(@munch $hdr $done [$($attrs)* #[$($attr)*]] $disp $kind $($rest)*);
};
(@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
$variant:ident { $($field:ident : $ftype:ty),* $(,)? } $(, $($rest:tt)*)?
) => {
$crate::define_errors!(@munch $hdr
[$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant { $($field : $ftype),* } }]
[] [] [] $($($rest)*)?);
};
(@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
$variant:ident $(, $($rest:tt)*)?
) => {
$crate::define_errors!(@munch $hdr
[$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant }]
[] [] [] $($($rest)*)?);
};
(@munch $hdr:tt $done:tt $attrs:tt $disp:tt [] $variant:ident $($rest:tt)*) => {
::core::compile_error!(::core::concat!(
"define_errors!: variant `",
::core::stringify!($variant),
"` needs a `#[kind(Name, ...)]` attribute"
));
};
(@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt) => {
::core::compile_error!("define_errors!: attributes must be followed by a variant");
};
(@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt $($rest:tt)+) => {
::core::compile_error!(::core::concat!(
"define_errors!: expected a unit or struct-like variant (`Name` or `Name { field: Type }`), found `",
::core::stringify!($($rest)+),
"`"
));
};
(@find_source) => {
::core::option::Option::None
};
(@find_source $field:ident $(, $rest:ident)*) => {
$crate::define_errors!(@find_source_match $field, $field $(, $rest)*)
};
(@find_source_match source, $source_field:ident $(, $rest:ident)*) => {
$crate::macros::ErrorSource::as_source($source_field)
};
(@find_source_match $field_name:ident, $field:ident $(, $rest:ident)*) => {
$crate::define_errors!(@find_source $($rest),*)
};
(@get_caption $kind:ident) => {
::core::stringify!($kind)
};
(@get_caption $kind:ident, caption = $caption:expr $(, $($rest:tt)*)?) => {
$caption
};
(@get_caption $kind:ident, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
$crate::define_errors!(@get_caption $kind $(, $($rest)*)?)
};
(@get_tag $target:ident, $default:expr) => {
$default
};
(@get_tag retryable, $default:expr, retryable = $val:expr $(, $($rest:tt)*)?) => {
$val
};
(@get_tag fatal, $default:expr, fatal = $val:expr $(, $($rest:tt)*)?) => {
$val
};
(@get_tag status, $default:expr, status = $val:expr $(, $($rest:tt)*)?) => {
$val
};
(@get_tag exit, $default:expr, exit = $val:expr $(, $($rest:tt)*)?) => {
$val
};
(@get_tag $target:ident, $default:expr, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
$crate::define_errors!(@get_tag $target, $default $(, $($rest)*)?)
};
(@format_display $display:literal) => {
::core::option::Option::Some(::std::format!($display))
};
(@format_display $display:literal, $($param:ident),+) => {
::core::option::Option::Some(::std::format!($display, $($param = $param),+))
};
(@format_display_field $field:ident) => {
$field
};
(@format_display_field $field:ident . $($rest:ident).+) => {
$field$(.$rest)+
};
(
$(
$(#[$meta:meta])* $vis:vis enum $name:ident {
$(
$(#[doc = $vdoc:expr])*
$(#[error(display = $display_a:literal $(, $param_a:ident)* $(,)?)])?
#[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)]
$(#[error(display = $display_b:literal $(, $param_b:ident)* $(,)?)])?
$variant:ident $( { $($field:ident : $ftype:ty),* $(,)? } )?
),* $(,)?
}
)*
) => {
$(
$crate::define_errors!(@emit [[$(#[$meta])*] [$vis] $name]
$({
[$(#[doc = $vdoc])*]
[
$($display_a $(, $param_a)*)?
$($display_b $(, $param_b)*)?
]
[$kind $(, $tag = $val)*]
$variant $( { $($field : $ftype),* } )?
})*
);
)*
};
(
$(
$(#[$meta:meta])* $vis:vis enum $name:ident { $($body:tt)* }
)*
) => {
$(
$crate::define_errors!(@munch [[$(#[$meta])*] [$vis] $name] [] [] [] [] $($body)*);
)*
};
}