1#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7#[non_exhaustive]
8pub enum ErrorLevel {
9 Debug,
11 Info,
13 Warning,
15 Error,
17 Critical,
19}
20
21#[non_exhaustive]
28pub struct ErrorContext<'a> {
29 pub caption: &'a str,
31 pub kind: &'a str,
33 pub level: ErrorLevel,
35 pub is_fatal: bool,
37 pub is_retryable: bool,
39}
40
41impl<'a> ErrorContext<'a> {
42 pub fn new(
48 caption: &'a str,
49 kind: &'a str,
50 level: ErrorLevel,
51 is_fatal: bool,
52 is_retryable: bool,
53 ) -> Self {
54 Self {
55 caption,
56 kind,
57 level,
58 is_fatal,
59 is_retryable,
60 }
61 }
62}
63
64use std::sync::OnceLock;
65
66type ErrorHookFn = Box<dyn Fn(ErrorContext<'_>) + Send + Sync + 'static>;
73
74static ERROR_HOOK: OnceLock<ErrorHookFn> = OnceLock::new();
76
77#[doc(hidden)]
78pub trait ErrorSource {
79 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)>;
80}
81
82impl ErrorSource for std::io::Error {
83 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84 Some(self)
85 }
86}
87
88impl ErrorSource for Box<dyn std::error::Error + Send + Sync> {
89 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
90 Some(self.as_ref())
91 }
92}
93
94impl ErrorSource for Box<dyn std::error::Error> {
95 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
96 Some(self.as_ref())
97 }
98}
99
100impl ErrorSource for Option<std::io::Error> {
101 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
102 self.as_ref()
103 .map(|error| error as &(dyn std::error::Error + 'static))
104 }
105}
106
107impl ErrorSource for Option<Box<dyn std::error::Error + Send + Sync>> {
108 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109 self.as_deref()
110 .map(|error| error as &(dyn std::error::Error + 'static))
111 }
112}
113
114impl ErrorSource for Option<Box<dyn std::error::Error>> {
115 fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
116 self.as_deref()
117 .map(|error| error as &(dyn std::error::Error + 'static))
118 }
119}
120
121#[deprecated(
148 since = "1.0.0",
149 note = "register_error_hook silently drops registration failures; use \
150 try_register_error_hook instead"
151)]
152pub fn register_error_hook<F>(callback: F)
153where
154 F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
155{
156 let _ = try_register_error_hook(callback);
157}
158
159pub fn try_register_error_hook<F>(callback: F) -> Result<(), &'static str>
183where
184 F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
185{
186 ERROR_HOOK
187 .set(Box::new(callback))
188 .map_err(|_| "Error hook already registered")
189}
190
191thread_local! {
192 static IN_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
196}
197
198struct InHookGuard;
200
201impl Drop for InHookGuard {
202 fn drop(&mut self) {
203 IN_HOOK.with(|flag| flag.set(false));
204 }
205}
206
207#[doc(hidden)]
215pub fn call_error_hook(caption: &str, kind: &str, is_fatal: bool, is_retryable: bool) {
216 let Some(hook) = ERROR_HOOK.get() else {
217 return;
218 };
219 if IN_HOOK.with(|flag| flag.replace(true)) {
220 return;
221 }
222 let _guard = InHookGuard;
223
224 let level = if is_fatal {
226 ErrorLevel::Critical
227 } else if !is_retryable {
228 ErrorLevel::Error
229 } else if kind == "Warning" {
230 ErrorLevel::Warning
231 } else if kind == "Debug" {
232 ErrorLevel::Debug
233 } else {
234 ErrorLevel::Info
235 };
236
237 let context = ErrorContext {
238 caption,
239 kind,
240 level,
241 is_fatal,
242 is_retryable,
243 };
244
245 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(context)));
251 if let Err(payload) = outcome {
252 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(payload)));
254 }
255}
256
257#[macro_export]
316macro_rules! define_errors {
317 (@emit [[$(#[$meta:meta])*] [$vis:vis] $name:ident]
324 $({
325 [$($vattr:tt)*]
326 [$($disp:tt)*]
327 [$kind:ident $(, $tag:ident = $val:expr)*]
328 $variant:ident $({ $($field:ident : $ftype:ty),* })?
329 })*
330 ) => {
331 $(#[$meta])* #[derive(::core::fmt::Debug)]
332 #[cfg_attr(feature = "serde", derive(::serde::Serialize))]
333 $vis enum $name {
334 $( $($vattr)* $variant $( { $($field : $ftype),* } )?, )*
335 }
336
337 const _: () = {
340 $( $( $crate::define_errors!(@check_tag $tag); )* )*
341 };
342
343 impl $name {
344 $(
345 $crate::__private::paste! {
346 pub fn [<$variant:lower>]($($($field : $ftype),*)?) -> Self {
347 let instance = Self::$variant $( { $($field),* } )?;
348 $crate::macros::call_error_hook(
349 instance.caption(),
350 instance.kind(),
351 instance.is_fatal(),
352 instance.is_retryable()
353 );
354 instance
355 }
356 }
357 )*
358
359 pub fn caption(&self) -> &'static str {
360 match self {
361 $( Self::$variant { .. } => {
362 $crate::define_errors!(@get_caption $kind $(, $tag = $val)*)
363 } ),*
364 }
365 }
366
367 pub fn kind(&self) -> &'static str {
368 match self {
369 $( Self::$variant { .. } => {
370 ::core::stringify!($kind)
371 } ),*
372 }
373 }
374
375 pub fn is_retryable(&self) -> bool {
376 match self {
377 $( Self::$variant { .. } => {
378 $crate::define_errors!(@get_tag retryable, false $(, $tag = $val)*)
379 } ),*
380 }
381 }
382
383 pub fn is_fatal(&self) -> bool {
384 match self {
385 $( Self::$variant { .. } => {
386 $crate::define_errors!(@get_tag fatal, false $(, $tag = $val)*)
387 } ),*
388 }
389 }
390
391 pub fn status_code(&self) -> u16 {
392 match self {
393 $( Self::$variant { .. } => {
394 $crate::define_errors!(@get_tag status, 500 $(, $tag = $val)*)
395 } ),*
396 }
397 }
398
399 pub fn exit_code(&self) -> i32 {
400 match self {
401 $( Self::$variant { .. } => {
402 $crate::define_errors!(@get_tag exit, 1 $(, $tag = $val)*)
403 } ),*
404 }
405 }
406 }
407
408 impl ::core::fmt::Display for $name {
409 #[allow(unused_variables)]
410 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
411 match self {
412 $( Self::$variant $( { $($field),* } )? => {
413 $crate::define_errors!(
414 @display f [$($disp)*] self.caption(); $variant $($($field)*)?
415 )
416 } ),*
417 }
418 }
419 }
420
421 impl ::std::error::Error for $name {
422 #[allow(unused_variables)]
423 fn source(&self) -> ::core::option::Option<&(dyn ::std::error::Error + 'static)> {
424 match self {
425 $( Self::$variant $( { $($field),* } )? => {
426 $crate::define_errors!(@find_source $( $($field),* )? )
427 } ),*
428 }
429 }
430 }
431 };
432
433 (@display $f:ident [$display:literal $(, $param:ident)*] $caption:expr; $variant:ident $($field:ident)*) => {
435 ::core::write!($f, $display $(, $param = $param)*)
436 };
437 (@display $f:ident [] $caption:expr; $variant:ident $($field:ident)*) => {{
441 ::core::write!($f, "{}: ", $caption)?;
442 $f.write_str(::core::stringify!($variant))?;
443 $(
444 ::core::write!($f, " | {} = ", ::core::stringify!($field))?;
445 $crate::define_errors!(@fmt_field $f, $field, $field)?;
446 )*
447 ::core::result::Result::Ok(())
448 }};
449 (@display $($rest:tt)*) => {
450 ::core::compile_error!(
451 "define_errors!: a variant may carry only one #[error(display = \"...\")] attribute"
452 )
453 };
454
455 (@fmt_field $f:ident, source, $field:ident) => {
459 ::core::write!($f, "{}", $field)
460 };
461 (@fmt_field $f:ident, $name:ident, $field:ident) => {
462 ::core::write!($f, "{:?}", $field)
463 };
464
465 (@check_tag caption) => {};
466 (@check_tag retryable) => {};
467 (@check_tag fatal) => {};
468 (@check_tag status) => {};
469 (@check_tag exit) => {};
470 (@check_tag $other:ident) => {
471 ::core::compile_error!(::core::concat!(
472 "define_errors!: unknown #[kind] tag `",
473 ::core::stringify!($other),
474 "`; expected one of `caption`, `retryable`, `fatal`, `status`, `exit`"
475 ));
476 };
477
478 (@munch $hdr:tt [$($done:tt)*] [] [] []) => {
489 $crate::define_errors!(@emit $hdr $($done)*);
490 };
491 (@munch $hdr:tt $done:tt [$($attrs:tt)*] [] $kind:tt
492 #[error(display = $display:literal $(, $param:ident)* $(,)?)] $($rest:tt)*
493 ) => {
494 $crate::define_errors!(@munch $hdr $done [$($attrs)*] [$display $(, $param)*] $kind $($rest)*);
495 };
496 (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[error $($bad:tt)*] $($rest:tt)*) => {
497 ::core::compile_error!(::core::concat!(
498 "define_errors!: expected a single `#[error(display = \"...\", field, ...)]` per variant, found `#[error",
499 ::core::stringify!($($bad)*),
500 "]`"
501 ));
502 };
503 (@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt []
504 #[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)] $($rest:tt)*
505 ) => {
506 $crate::define_errors!(@munch $hdr $done [$($attrs)*] $disp [$kind $(, $tag = $val)*] $($rest)*);
507 };
508 (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[kind $($bad:tt)*] $($rest:tt)*) => {
509 ::core::compile_error!(::core::concat!(
510 "define_errors!: expected a single `#[kind(Name, tag = value, ...)]` per variant, found `#[kind",
511 ::core::stringify!($($bad)*),
512 "]`"
513 ));
514 };
515 (@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt $kind:tt #[$($attr:tt)*] $($rest:tt)*) => {
516 $crate::define_errors!(@munch $hdr $done [$($attrs)* #[$($attr)*]] $disp $kind $($rest)*);
517 };
518 (@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
519 $variant:ident { $($field:ident : $ftype:ty),* $(,)? } $(, $($rest:tt)*)?
520 ) => {
521 $crate::define_errors!(@munch $hdr
522 [$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant { $($field : $ftype),* } }]
523 [] [] [] $($($rest)*)?);
524 };
525 (@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
526 $variant:ident $(, $($rest:tt)*)?
527 ) => {
528 $crate::define_errors!(@munch $hdr
529 [$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant }]
530 [] [] [] $($($rest)*)?);
531 };
532 (@munch $hdr:tt $done:tt $attrs:tt $disp:tt [] $variant:ident $($rest:tt)*) => {
533 ::core::compile_error!(::core::concat!(
534 "define_errors!: variant `",
535 ::core::stringify!($variant),
536 "` needs a `#[kind(Name, ...)]` attribute"
537 ));
538 };
539 (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt) => {
540 ::core::compile_error!("define_errors!: attributes must be followed by a variant");
541 };
542 (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt $($rest:tt)+) => {
543 ::core::compile_error!(::core::concat!(
544 "define_errors!: expected a unit or struct-like variant (`Name` or `Name { field: Type }`), found `",
545 ::core::stringify!($($rest)+),
546 "`"
547 ));
548 };
549
550 (@find_source) => {
554 ::core::option::Option::None
555 };
556
557 (@find_source $field:ident $(, $rest:ident)*) => {
558 $crate::define_errors!(@find_source_match $field, $field $(, $rest)*)
559 };
560
561 (@find_source_match source, $source_field:ident $(, $rest:ident)*) => {
562 $crate::macros::ErrorSource::as_source($source_field)
563 };
564
565 (@find_source_match $field_name:ident, $field:ident $(, $rest:ident)*) => {
566 $crate::define_errors!(@find_source $($rest),*)
567 };
568
569 (@get_caption $kind:ident) => {
570 ::core::stringify!($kind)
571 };
572
573 (@get_caption $kind:ident, caption = $caption:expr $(, $($rest:tt)*)?) => {
574 $caption
575 };
576
577 (@get_caption $kind:ident, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
578 $crate::define_errors!(@get_caption $kind $(, $($rest)*)?)
579 };
580
581 (@get_tag $target:ident, $default:expr) => {
582 $default
583 };
584
585 (@get_tag retryable, $default:expr, retryable = $val:expr $(, $($rest:tt)*)?) => {
586 $val
587 };
588
589 (@get_tag fatal, $default:expr, fatal = $val:expr $(, $($rest:tt)*)?) => {
590 $val
591 };
592
593 (@get_tag status, $default:expr, status = $val:expr $(, $($rest:tt)*)?) => {
594 $val
595 };
596
597 (@get_tag exit, $default:expr, exit = $val:expr $(, $($rest:tt)*)?) => {
598 $val
599 };
600
601 (@get_tag $target:ident, $default:expr, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
602 $crate::define_errors!(@get_tag $target, $default $(, $($rest)*)?)
603 };
604
605 (@format_display $display:literal) => {
606 ::core::option::Option::Some(::std::format!($display))
607 };
608
609 (@format_display $display:literal, $($param:ident),+) => {
610 ::core::option::Option::Some(::std::format!($display, $($param = $param),+))
611 };
612
613 (@format_display_field $field:ident) => {
614 $field
615 };
616
617 (@format_display_field $field:ident . $($rest:ident).+) => {
618 $field$(.$rest)+
619 };
620
621 (
629 $(
630 $(#[$meta:meta])* $vis:vis enum $name:ident {
631 $(
632 $(#[doc = $vdoc:expr])*
633 $(#[error(display = $display_a:literal $(, $param_a:ident)* $(,)?)])?
634 #[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)]
635 $(#[error(display = $display_b:literal $(, $param_b:ident)* $(,)?)])?
636 $variant:ident $( { $($field:ident : $ftype:ty),* $(,)? } )?
637 ),* $(,)?
638 }
639 )*
640 ) => {
641 $(
642 $crate::define_errors!(@emit [[$(#[$meta])*] [$vis] $name]
643 $({
644 [$(#[doc = $vdoc])*]
645 [
646 $($display_a $(, $param_a)*)?
647 $($display_b $(, $param_b)*)?
648 ]
649 [$kind $(, $tag = $val)*]
650 $variant $( { $($field : $ftype),* } )?
651 })*
652 );
653 )*
654 };
655
656 (
658 $(
659 $(#[$meta:meta])* $vis:vis enum $name:ident { $($body:tt)* }
660 )*
661 ) => {
662 $(
663 $crate::define_errors!(@munch [[$(#[$meta])*] [$vis] $name] [] [] [] [] $($body)*);
664 )*
665 };
666}