wherr Crate Documentation
The wherr crate provides utilities to embed where errors originate from by enhancing them with additional file and line number information.
Table of Contents
Installation
Add the wherr crate to your Cargo.toml:
[]
= "0.1"
Usage
To understand the benefits of the wherr crate, let's first observe the problem it aims to solve:
Without #[wherr]:
Running this code would produce:
sum1 = 30
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', wherr/examples/macro.rs:12:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
wherr/examples/macro.rs:12:47 is this line:
let sum2 = add_two.unwrap;
But there is no information on what line of code down the stack that caused this error.
In this specific case, it's easy to analyse and understand, but if there would be lots of nested layers, it can sometimes be difficult to figure out where it comes from.
Using the wherr procedural macro
By adding #[wherr], the location of the error becomes visible in the error message:
use wherr;
The resulting error is:
sum1 = 30
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error at wherr/examples/macro.rs:7. Original error: ParseIntError { kind: InvalidDigit }', wherr/examples/macro.rs:15:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
In addition, we now also got another location, wherr/examples/macro.rs:7:
let i2 = i64from_str_radix?;
This is where the error was created and returned.
The file and line info can also be extracted from the Wherr struct,
that wraps the original Err.
match add_two
Error at file: 'wherr/examples/macro.rs', line: 7. Original error: invalid digit found in string
It also works through multiple nested layers:
use wherr;
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error at wherr/examples/nested.rs:7. Original error: ParseIntError { kind: InvalidDigit }', wherr/examples/nested.rs:18:49
Here, wherr/examples/nested.rs:7 is this line:
let i2 = i64from_str_radix?;
That is, the line in add_two() where the error happened, propagated to add_four(), and then to main().
API Reference
Wherr
Represents an error that includes file and line number information.
Methods:
new(err: Box<dyn std::error::Error>, file: &'static str, line: u32) -> Self: Creates a newWherrerror that wraps another error, providing additional context.
wherrapper
This internal utility function is used by the procedural macro to wrap errors with file and line information.
wherr procedural macro
A procedural macro that auto-wraps errors (using the ? operator) inside a function with file and line number details.
Contributing
If you're interested in contributing to wherr, please follow standard Rust community guidelines and submit a PR on our repository.
License
Please refer to the LICENSE file in the root directory of the crate for license details.