From 16f2fbcb6d26abecd324bf5be7d0dcc1291bf23f Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Wed, 27 Jan 2021 14:57:59 -0500 Subject: [PATCH] docs: Improve style guide about using Snafu (#695) --- docs/style_guide.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/docs/style_guide.md b/docs/style_guide.md index effcaa9b44..6eee78a11b 100644 --- a/docs/style_guide.md +++ b/docs/style_guide.md @@ -165,6 +165,47 @@ input_reader })?; ``` +*Hint for `Box` in Snafu*: + +If your error contains a trait object (e.g. `Box`), in order to use `context()` you need to wrap the error in a `Box` : + +```rust +#[derive(Debug, Snafu)] +pub enum Error { + + #[snafu(display("gRPC planner got error listing partition keys: {}", source))] + ListingPartitions { + source: Box, + }, +} + +... + + // Wrap error in a box prior to calling context() +database + .partition_keys() + .await + .map_err(|e| Box::new(e) as _) + .context(ListingPartitions)?; + +``` + +Note the `as _` in the `map_err` call. Without it, you may get an error such as: + +``` +error[E0271]: type mismatch resolving `>::Source == Box<::Error>` + --> query/src/frontend/influxrpc.rs:63:14 + | +63 | .context(ListingPartitions)?; + | ^^^^^^^ expected trait object `dyn snafu::Error`, found associated type + | + = note: expected struct `Box<(dyn snafu::Error + Send + Sync + 'static)>` + found struct `Box<::Error>` + = help: consider constraining the associated type `::Error` to `(dyn snafu::Error + Send + Sync + 'static)` + = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html +``` + + ### Each error cause in a module should have a distinct Error enum Specific error types are preferred over a generic error with a `message` or `kind` field.