format_err

Macro format_err 

macro_rules! format_err {
    ( $message:literal $(,)? ) => { ... };
    ( $message:literal , $( $args:tt )* ) => { ... };
    ( $error:expr $(,)? ) => { ... };
}
Expand description

Construct an Error via string formatting or another error.

Like anyhow::format_err! or anyhow::anyhow! but for wasmtime::Error.

§String Formatting

When a string literal is the first argument, it is interpreted as a format string template and the rest of the arguments are format arguments:

use wasmtime::{format_err, Error};

let x = 42;
let error: Error = format_err!("x is {x}");
assert_eq!(error.to_string(), "x is 42");

let error: Error = format_err!("x / 2 is {}", x / 2);
assert_eq!(error.to_string(), "x / 2 is 21");

let error: Error = format_err!("x + 1 is {y}", y = x + 1);
assert_eq!(error.to_string(), "x + 1 is 43");

§From Another Error

When a string literal is not the first argument, then it is treated as a foreign error and is converted into an Error. The argument must be of a type that can be passed to either Error::new or Error::msg:

#![cfg(feature = "std")]
use std::fmt;
use wasmtime::{format_err, Error};

#[derive(Debug)]
struct SomeOtherError(u32);

impl fmt::Display for SomeOtherError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "some other error (code {})", self.0)
    }
}

impl std::error::Error for SomeOtherError {}

let error: Error = format_err!(SomeOtherError(36));
assert!(error.is::<SomeOtherError>());
assert_eq!(error.to_string(), "some other error (code 36)");

§From an anyhow::Error

The format_err! macro can always convert an anyhow::Error into a wasmtime::Error, but when the "anyhow" cargo feature is enabled the resulting error will also return true for error.is::<anyhow::Error>() invocations.

#![cfg(feature = "anyhow")]
use wasmtime::format_err;

let anyhow_error: anyhow::Error = anyhow::anyhow!("aw crap");
let wasmtime_error: wasmtime::Error = format_err!(anyhow_error);
assert!(wasmtime_error.is::<anyhow::Error>());