Trait Context
trait Context<T, E>: context::private::Sealed
Provides the context method for Result.
This trait is sealed and cannot be implemented for types outside of
anyhow.
Example
use ;
use fs;
use PathBuf;
When printed, the outermost context would be printed first and the lower level underlying causes would be enumerated below.
Error: Failed to read instrs from ./path/to/instrs.json
Caused by:
No such file or directory (os error 2)
Refer to the Display representations documentation for other forms in which this context chain can be rendered.
Effect on downcasting
After attaching context of type C onto an error of type E, the resulting
anyhow::Error may be downcast to C or to E.
That is, in codebases that rely on downcasting, Anyhow's context supports both of the following use cases:
-
Attaching context whose type is insignificant onto errors whose type is used in downcasts.
In other error libraries whose context is not designed this way, it can be risky to introduce context to existing code because new context might break existing working downcasts. In Anyhow, any downcast that worked before adding context will continue to work after you add a context, so you should freely add human-readable context to errors wherever it would be helpful.
# use bail; # use Error; # # # # ; # # # use ; -
Attaching context whose type is used in downcasts onto errors whose type is insignificant.
Some codebases prefer to use machine-readable context to categorize lower level errors in a way that will be actionable to higher levels of the application.
# use bail; # use Error; # # # # ; # # # use ;
Required Methods
fn context<C>(self: Self, context: C) -> Result<T, Error> where C: Display + Send + Sync + 'staticWrap the error value with additional context.
fn with_context<C, F>(self: Self, f: F) -> Result<T, Error> where C: Display + Send + Sync + 'static, F: FnOnce() -> CWrap the error value with additional context that is evaluated lazily only once an error does occur.