Skip to main content

scoped_error/
ext.rs

1// Copyright (C) 2026 Kan-Ru Chen <kanru@kanru.info>
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5//! Extension traits for error handling.
6//!
7//! This module provides [`ErrorExt`], which adds convenient methods to
8/// all types implementing [`std::error::Error`].
9use std::error::Error;
10
11use crate::ErrorReport;
12
13/// Extension trait for [`std::error::Error`].
14///
15/// This trait is implemented for all types that implement `Error`,
16/// providing additional methods for working with errors.
17///
18/// # Example
19///
20/// ```
21/// use std::error::Error;
22/// use scoped_error::ErrorExt;
23///
24/// fn handle_error(e: impl Error + 'static) {
25///     let report = e.report();
26///     println!("{}", report);
27/// }
28/// ```
29pub trait ErrorExt {
30    /// Generate a formatted error report for this error.
31    ///
32    /// The report includes the error message and all causes in the chain,
33    /// formatted for human readability.
34    ///
35    /// # Example
36    ///
37    /// ```
38    /// use scoped_error::{Error, expect_error, ErrorExt};
39    ///
40    /// let result: Result<(), Error> = expect_error("Outer", || {
41    ///     Err("Inner")?;
42    ///     Ok(())
43    /// });
44    ///
45    /// if let Err(e) = result {
46    ///     println!("{}", e.report());
47    /// }
48    /// ```
49    fn report(&self) -> ErrorReport<'_>;
50}
51
52impl<T> ErrorExt for T
53where
54    T: Error + 'static,
55{
56    fn report(&self) -> ErrorReport<'_> {
57        ErrorReport(self)
58    }
59}