disperror 0.1.1

`Display`ing errors instead of `Debug`ging them when returned from `main`.
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented2 out of 2 items with examples
  • Size
  • Source code size: 5.68 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 278.32 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 7s Average build duration of successful builds.
  • all releases: 9s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • PRO-2684/disperror
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • PRO-2684

disperror

Displaying errors instead of Debugging them when returned from main.

Usage

Simply wrap your error type MyError in a DispError:

- fn main() -> Result<(), MyError> {
+ use disperror::DispError;
+ fn main() -> Result<(), DispError<MyError>> {

Note that MyError must implement std::error::Error.

Example

use disperror::DispError;

fn main() -> Result<(), DispError<std::io::Error>> {
    let contents = std::fs::read_to_string("nonexistent_file.txt")?;
    println!("{}", contents);
    Ok(())
}

Should Display the following error message if that file does not exist:

Error: No such file or directory (os error 2)

Instead of the usual Debug output:

Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }

Implementation

The DispError type is a simple wrapper around an error type E that implements std::error::Error:

use std::error::Error;

pub struct DispError<E: Error> {
    error: E,
}

The Debug implementation of DispError forwards to the Display implementation of the inner error:

use std::{error::Error, fmt::Debug};
#
# pub struct DispError<E: Error> {
#     error: E,
# }

impl<E: Error> Debug for DispError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.error)
    }
}

In addition, DispError implements From<E> for implicit conversion:

# use std::{error::Error, fmt::Debug};
#
# pub struct DispError<E: Error> {
#     error: E,
# }

impl<E: Error> From<E> for DispError<E> {
    fn from(error: E) -> Self {
        Self { error }
    }
}

In this way, when an error of type E is returned from main, it is automatically converted to a DispError<E>. When the Err variant of a Result is returned from main, the Debug implementation is used to print the error message, thus forwarding to the Display implementation of the inner error.

Notes

This project is heavily inspired by main_error. If you're working with Box<dyn std::error::Error> in your main function, use main_error instead. Here's a quick comparison:

disperror main_error
Library size Tiny Small
Overhead None Negligible
Dynamic dispatch
Usage DispError<E> MainError