pub trait RootError<M, Target: Error2>: SourceToTarget<M, (), (), Target> + Sized {
// Provided methods
fn build(self) -> Target { ... }
fn build_with_location(self, location: Location) -> Target { ... }
fn fail<T>(self) -> Result<T, Target> { ... }
fn fail_with_location<T>(self, location: Location) -> Result<T, Target> { ... }
}Expand description
Convenience methods for creating root errors.
RootError provides .build() and .fail() for creating errors that
represent new error origins (not wrapping other errors).
§Root Error Pattern
A root error only has a backtrace field (no source):
use error2::prelude::*;
#[derive(Debug, Error2)]
pub enum AppError {
#[error2(display("invalid ID: {id}"))]
InvalidId { id: i64, backtrace: Backtrace },
#[error2(display("channel closed"))]
ChannelClosed { backtrace: Backtrace },
}§Using .build()
Create an error instance:
if id < 0 {
let error = InvalidId2 { id }.build();
// Use error...
}§Using .fail()
Create and return an error in one step:
fn validate(id: i64) -> Result<(), AppError> {
if id < 0 {
return InvalidId2 { id }.fail();
}
Ok(())
}§Automatic Location Tracking
Both .build() and .fail() automatically capture the caller’s
location using #[track_caller], which is included in the backtrace.
use regex::Regex;
let err = InvalidId2 { id: -1 }.build();
let msg = err.backtrace().error_message();
// Full error format with location tracking:
// AppError: invalid ID: -1
// at /path/to/file.rs:683:33
let re = Regex::new(concat!(
r"(?s)^.+AppError: invalid ID: -1",
r"\n at .+\.rs:\d+:\d+$",
))
.unwrap();
assert!(re.is_match(msg.as_ref()));Provided Methods§
Sourcefn build(self) -> Target
fn build(self) -> Target
Creates a root error instance.
Automatically captures the caller’s location.
Sourcefn build_with_location(self, location: Location) -> Target
fn build_with_location(self, location: Location) -> Target
Creates a root error with explicit location.
Sourcefn fail<T>(self) -> Result<T, Target>
fn fail<T>(self) -> Result<T, Target>
Creates and returns a root error as Err(...).
Convenient for returning errors directly.
Sourcefn fail_with_location<T>(self, location: Location) -> Result<T, Target>
fn fail_with_location<T>(self, location: Location) -> Result<T, Target>
Creates and returns error with explicit location.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.