---
title: ensure
summary: Return early with an error if a condition is not satisfied.
url: https://www.fastly.com/documentation/reference/compute/sdks/rust/fastly/error/macro.ensure/
---

**Kind:** Macro  
**Module:** [error](https://www.fastly.com/documentation/reference/compute/sdks/rust/fastly/error/)  
**Package:** fastly 0.13.1

```rust
macro_rules! ensure {
    ($cond:expr $(,)?) => { ... };
    ($cond:expr, $msg:literal $(,)?) => { ... };
    ($cond:expr, $err:expr $(,)?) => { ... };
    ($cond:expr, $fmt:expr, $($arg:tt)*) => { ... };
}
```

Return early with an error if a condition is not satisfied.

This macro is equivalent to
<code>if !$cond { return Err(anyhow!($args\...)); }</code>.

The surrounding function's or closure's return value is required to be
<code>Result&lt;_, [anyhow::Error][crate::Error]&gt;</code>.

Analogously to `assert!`, `ensure!` takes a condition and exits the function
if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
rather than panicking.

## Example

```rust
ensure!(user == 0, "only user 0 is allowed");
```

```rust
#[derive(Error, Debug)]
enum ScienceError {
    #[error("recursion limit exceeded")]
    RecursionLimitExceeded,
    ...
}

ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
```
