Skip to content

Commit

Permalink
Show source by default, add feature to hide it (#60)
Browse files Browse the repository at this point in the history
* Show source by default, add feature to hide it

close #59

Changes the default behavior so that the output in the readme now matches the output a user would see when they use the library. Specifically, it now includes the original `std::io::Error` in the output.

It introduces a feature `anyhow`. By default:

- By default: fs-err will include `std::io::Error` in the Display output, and return `None` from `Error::source()`
- With `anyhow` fs-err will not include std::io::Error in the Display output, and return `Some(std::io::Error)` from `Error::source()`

This is based on the guidance from #51. That discussion links to this 2020 discussion rust-lang/project-error-handling#23 that suggests that you should either print the source and return `None` from `Error::source()` (https://doc.rust-lang.org/std/error/trait.Error.html#method.source) or not print anything and return `Some(E)`.

This allows users of anyhow (or similar) libraries to configure fs-err for the behavior they desire, while not hiding information by default from unsuspecting adopters that are not using those libraries. It optimizes for the case of accidentally showing extra information that a user can then investigate and disable, rather than hiding information that the user might not realize is missing.

* Update feature name

I discussed the logic here #59 (comment).

The prior suggested name "anyhow" was a little too specific/esoteric and in the event that the feature flag outlives the popularity of `anyhow` it wouldn't make sense.

This suggested name tries to focus on the behavior outcome of the feature. It empowers callers to format the "called by" information however they want by:

- Providing a source of that data (Error::source)
- Not formatting emitting that data in `Display`

* Update feature name to `expose_original_error`

* Document why that feature disables displaying error

At a glance it's not clear why that logic exists based solely on the feature name. Adding a doc here clarifies the intent.
  • Loading branch information
schneems authored Oct 23, 2024
1 parent 7a49316 commit df8f93a
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,9 @@ jobs:
command: check
args: --features tokio
if: ${{ matrix.rust_version == 'stable' || matrix.rust_version == 'beta' }}

- name: cargo check --features expose_original_error
uses: actions-rs/cargo@v1
with:
command: check
args: --features expose_original_error
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# fs-err Changelog

* Change errors to output original `std::io::Error` information Display by default. This functionality can be disabled for [anyhow](https://docs.rs/anyhow/latest/anyhow/) users by using the new feature `expose_original_error` ([#60](https://github.com/andrewhickman/fs-err/pull/60)).

## 2.11.0

* Added the first line of the standard library documentation to each function's rustdocs, to make them more useful in IDEs ([#50](https://github.com/andrewhickman/fs-err/issues/45))
Expand Down
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ serde_json = "1.0.64"
# Adds I/O safety traits, introduced in Rust 1.63
io_safety = []

# Allow custom formatting of the error source
#
# When enabled errors emit `std::error::Error::source()` as Some (default is `None`) and
# no longer include the original `std::io::Error` source in the `Display` implementation.
# This is useful if errors are wrapped in another library such as Anyhow.
expose_original_error = []

[package.metadata.release]
tag-name = "{{version}}"
sign-tag = true
Expand Down
28 changes: 26 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,13 @@ impl fmt::Display for Error {
E::ReadAt => write!(formatter, "failed to read with offset from `{}`", path),
#[cfg(unix)]
E::WriteAt => write!(formatter, "failed to write with offset to `{}`", path),
}
}?;

// The `expose_original_error` feature indicates the caller should display the original error
#[cfg(not(feature = "expose_original_error"))]
write!(formatter, " caused by: {}", self.source)?;

Ok(())
}
}

Expand All @@ -108,6 +114,12 @@ impl StdError for Error {
self.source()
}

#[cfg(not(feature = "expose_original_error"))]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}

#[cfg(feature = "expose_original_error")]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.source)
}
Expand Down Expand Up @@ -188,7 +200,13 @@ impl fmt::Display for SourceDestError {
SourceDestErrorKind::SymlinkDir => {
write!(formatter, "failed to symlink dir from {} to {}", from, to)
}
}
}?;

// The `expose_original_error` feature indicates the caller should display the original error
#[cfg(not(feature = "expose_original_error"))]
write!(formatter, " caused by: {}", self.source)?;

Ok(())
}
}

Expand All @@ -197,6 +215,12 @@ impl StdError for SourceDestError {
self.source()
}

#[cfg(not(feature = "expose_original_error"))]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}

#[cfg(feature = "expose_original_error")]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.source)
}
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ failed to open file `does not exist.txt`
caused by: The system cannot find the file specified. (os error 2)
```
> Note: Users of `anyhow` or other libraries that format an Error's sources can enable the `expose_original_error` feature to control the formatting of the orginal error message.
> When enabled, the `std::fmt::Display` implementation will emit the failed operation and paths but not the original `std::io::Error`. It will instead provide access via [Error::source](https://doc.rust-lang.org/std/error/trait.Error.html#method.source), which will be used by `anyhow` (or similar) libraries.
# Usage
fs-err's API is the same as [`std::fs`][std::fs], so migrating code to use it is easy.
Expand Down

0 comments on commit df8f93a

Please sign in to comment.