| 1 |
--- |
| 2 |
title: Bevy Error Context Messages |
| 3 |
authors: ["@cookie1170"] |
| 4 |
pull_requests: [24528] |
| 5 |
--- |
| 6 |
|
| 7 |
Similar to the popular `anyhow` crate, `BevyError` now provides an ergonomic way to attach extra context to an error using the `context` method, |
| 8 |
which also allows creating a `Result<T, BevyError>` from an `Option<T>`. |
| 9 |
|
| 10 |
This makes it easier to trace back errors with human-readable messages without looking at verbose backtraces. |
| 11 |
|
| 12 |
```rs |
| 13 |
fn fallible() -> Result<(), BevyError> { |
| 14 |
// This produces the error message `Failed to parse number: invalid digit found in string` |
| 15 |
let parsed: usize = "I am not a number" |
| 16 |
.parse() |
| 17 |
.context("Failed to parse number")?; |
| 18 |
|
| 19 |
Ok(()) |
| 20 |
} |
| 21 |
``` |
| 22 |
|
| 23 |
`with_context` may be used to produce the error string with a closure instead. |
| 24 |
|
| 25 |
If multiple `context`s were used on the same `BevyError`, they're enumerated below: |
| 26 |
|
| 27 |
```rs |
| 28 |
fn fallible() -> Result<Package, BevyError> { |
| 29 |
let path = "package.json"; |
| 30 |
let package = std::fs::read_to_string(path) |
| 31 |
.with_context(|| format!("Failed to read {path}"))?; |
| 32 |
|
| 33 |
serde_json::parse(&package)? |
| 34 |
} |
| 35 |
|
| 36 |
fn uses_fallible() -> Result<(), BevyError> { |
| 37 |
let package = fallible().context("Failed to parse package.json")?; |
| 38 |
// Use `package`... |
| 39 |
} |
| 40 |
``` |
| 41 |
|
| 42 |
Will produce the following error if `package.json` is missing: |
| 43 |
|
| 44 |
```rs |
| 45 |
Failed to parse package.json |
| 46 |
|
| 47 |
Caused by: |
| 48 |
Failed to read package.json |
| 49 |
No such file or directory (os error 2) |
| 50 |
``` |