[][src]Struct anyhow::Error

pub struct Error { /* fields omitted */ }

The Error type, a wrapper around a dynamic error type.

Error works a lot like Box<dyn std::error::Error>, but with these differences:

  • Error requires that the error is Send, Sync, and 'static.
  • Error guarantees that a backtrace is available, even if the underlying error type does not provide one.
  • Error is represented as a narrow pointer — exactly one word in size instead of two.

Methods

impl Error[src]

pub fn new<E>(error: E) -> Self where
    E: StdError + Send + Sync + 'static, 
[src]

Create a new error object from any error type.

The error type must be threadsafe and 'static, so that the Error will be as well.

If the error type does not provide a backtrace, a backtrace will be created here to ensure that a backtrace exists.

pub fn context<C>(self, context: C) -> Self where
    C: Display + Send + Sync + 'static, 
[src]

Wrap the error value with additional context.

For attaching context to a Result as it is propagated, the Context extension trait may be more convenient than this function.

The primary reason to use error.context(...) instead of result.context(...) via the Context trait would be if the context needs to depend on some data held by the underlying error:

use anyhow::Result;
use std::fs::File;
use std::path::Path;

struct ParseError {
    line: usize,
    column: usize,
}

fn parse_impl(file: File) -> Result<T, ParseError> {
    ...
}

pub fn parse(path: impl AsRef<Path>) -> Result<T> {
    let file = File::open(&path)?;
    parse_impl(file).map_err(|error| {
        let context = format!(
            "only the first {} lines of {} are valid",
            error.line, path.as_ref().display(),
        );
        anyhow::Error::new(error).context(context)
    })
}

pub fn backtrace(&self) -> &Backtrace[src]

Get the backtrace for this Error.

Backtraces are only available on the nightly channel. Tracking issue: rust-lang/rust#53487.

In order for the backtrace to be meaningful, the environment variable RUST_LIB_BACKTRACE=1 must be defined. Backtraces are somewhat expensive to capture in Rust, so we don't necessarily want to be capturing them all over the place all the time.

Important traits for Chain<'a>
pub fn chain(&self) -> Chain[src]

An iterator of the chain of source errors contained by this Error.

This iterator will visit every error in the cause chain of this error object, beginning with the error that this error object was created from.

Example

use anyhow::Error;
use std::io;

pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
    for cause in error.chain() {
        if let Some(io_error) = cause.downcast_ref::<io::Error>() {
            return Some(io_error.kind());
        }
    }
    None
}

pub fn root_cause(&self) -> &(dyn StdError + 'static)[src]

The lowest level cause of this error — this error's cause's cause's cause etc.

The root cause is the last error in the iterator produced by chain().

pub fn is<E>(&self) -> bool where
    E: Display + Debug + Send + Sync + 'static, 
[src]

Returns true if E is the type wrapped by this error object.

pub fn downcast<E>(self) -> Result<E, Self> where
    E: Display + Debug + Send + Sync + 'static, 
[src]

Attempt to downcast the error object to a concrete type.

pub fn downcast_ref<E>(&self) -> Option<&E> where
    E: Display + Debug + Send + Sync + 'static, 
[src]

Downcast this error object by reference.

Example

// If the error was caused by redaction, then return a tombstone instead
// of the content.
match root_cause.downcast_ref::<DataStoreError>() {
    Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
    None => Err(error),
}

pub fn downcast_mut<E>(&mut self) -> Option<&mut E> where
    E: Display + Debug + Send + Sync + 'static, 
[src]

Downcast this error object by mutable reference.

Methods from Deref<Target = dyn StdError + Send + Sync + 'static>

pub fn is<T>(&self) -> bool where
    T: 'static + Error
1.3.0[src]

Returns true if the boxed type is the same as T

pub fn downcast_ref<T>(&self) -> Option<&T> where
    T: 'static + Error
1.3.0[src]

Returns some reference to the boxed value if it is of type T, or None if it isn't.

pub fn downcast_mut<T>(&mut self) -> Option<&mut T> where
    T: 'static + Error
1.3.0[src]

Returns some mutable reference to the boxed value if it is of type T, or None if it isn't.

pub fn is<T>(&self) -> bool where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn downcast_ref<T>(&self) -> Option<&T> where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn downcast_mut<T>(&mut self) -> Option<&mut T> where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn is<T>(&self) -> bool where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn downcast_ref<T>(&self) -> Option<&T> where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn downcast_mut<T>(&mut self) -> Option<&mut T> where
    T: 'static + Error
1.3.0[src]

Forwards to the method defined on the type dyn Error.

pub fn iter_chain(&self) -> ErrorIter[src]

🔬 This is a nightly-only experimental API. (error_iter)

Returns an iterator starting with the current error and continuing with recursively calling source.

Examples

#![feature(error_iter)]
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct A;

#[derive(Debug)]
struct B(Option<Box<dyn Error + 'static>>);

impl fmt::Display for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "A")
    }
}

impl fmt::Display for B {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "B")
    }
}

impl Error for A {}

impl Error for B {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.as_ref().map(|e| e.as_ref())
    }
}

let b = B(Some(Box::new(A)));

// let err : Box<Error> = b.into(); // or
let err = &b as &(dyn Error);

let mut iter = err.iter_chain();

assert_eq!("B".to_string(), iter.next().unwrap().to_string());
assert_eq!("A".to_string(), iter.next().unwrap().to_string());
assert!(iter.next().is_none());
assert!(iter.next().is_none());

pub fn iter_sources(&self) -> ErrorIter[src]

🔬 This is a nightly-only experimental API. (error_iter)

Returns an iterator starting with the source of this error and continuing with recursively calling source.

Examples

#![feature(error_iter)]
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct A;

#[derive(Debug)]
struct B(Option<Box<dyn Error + 'static>>);

#[derive(Debug)]
struct C(Option<Box<dyn Error + 'static>>);

impl fmt::Display for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "A")
    }
}

impl fmt::Display for B {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "B")
    }
}

impl fmt::Display for C {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "C")
    }
}

impl Error for A {}

impl Error for B {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.as_ref().map(|e| e.as_ref())
    }
}

impl Error for C {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.as_ref().map(|e| e.as_ref())
    }
}

let b = B(Some(Box::new(A)));
let c = C(Some(Box::new(b)));

// let err : Box<Error> = c.into(); // or
let err = &c as &(dyn Error);

let mut iter = err.iter_sources();

assert_eq!("B".to_string(), iter.next().unwrap().to_string());
assert_eq!("A".to_string(), iter.next().unwrap().to_string());
assert!(iter.next().is_none());
assert!(iter.next().is_none());

Trait Implementations

impl Send for Error[src]

impl Sync for Error[src]

impl Drop for Error[src]

impl<E> From<E> for Error where
    E: StdError + Send + Sync + 'static, 
[src]

impl From<Error> for Box<dyn StdError + Send + Sync + 'static>[src]

impl Display for Error[src]

impl Debug for Error[src]

impl Deref for Error[src]

type Target = dyn StdError + Send + Sync + 'static

The resulting type after dereferencing.

impl DerefMut for Error[src]

Auto Trait Implementations

impl Unpin for Error

impl UnwindSafe for Error

impl RefUnwindSafe for Error

Blanket Implementations

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> From<T> for T[src]

impl<T> From<!> for T[src]

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]