cargo anyhow 1.0.18

latest releases: 1.0.83, 1.0.82, 1.0.81...
4 years ago
  • Support downcasting errors with context to the context's type C or to the underlying error type E (#34)

    That is, in codebases that rely on downcasting, Anyhow's context now 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 anyhow::{Context, Result};
      
      fn do_it() -> Result<()> {
          helper().context("failed to complete the work")?;
          ...
      }
      
      fn main() {
          let err = do_it().unwrap_err();
          if let Some(e) = err.downcast_ref::<SuspiciousError>() {
              // If helper() returned SuspiciousError, this downcast will
              // correctly succeed even with the context in between.
          }
      }
    • 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 anyhow::{Context, Result};
      
      fn do_it() -> Result<()> {
          helper().context(HelperFailed)?;
          ...
      }
      
      fn main() {
          let err = do_it().unwrap_err();
          if let Some(e) = err.downcast_ref::<HelperFailed>() {
              // If helper failed, this downcast will succeed because
              // HelperFailed is the context that has been attached to
              // that error.
          }
      }

Don't miss a new anyhow release

NewReleases is sending notifications on new releases.