|
| 1 | +# Strings and custom fail type |
| 2 | + |
| 3 | +This pattern is an hybrid between the [_An Error and ErrorKind pair_](./error-errorkind.md) and |
| 4 | +[_Using the Error type_](./use-error.md). |
| 5 | + |
| 6 | +Such an error type can be implemented in the same way that what was shown in |
| 7 | +the [_An Error and ErrorKind pair_](./error-errorkind.md) pattern, but here, the context is a |
| 8 | +simple string: |
| 9 | + |
| 10 | +```rust |
| 11 | +extern crate core; |
| 12 | +extern crate failure; |
| 13 | + |
| 14 | +use core::fmt::{self, Display}; |
| 15 | +use failure::{Backtrace, Context, Fail, ResultExt}; |
| 16 | + |
| 17 | +#[derive(Debug)] |
| 18 | +pub struct MyError { |
| 19 | + inner: Context<String>, |
| 20 | +} |
| 21 | + |
| 22 | +impl Fail for MyError { |
| 23 | + fn cause(&self) -> Option<&Fail> { |
| 24 | + self.inner.cause() |
| 25 | + } |
| 26 | + |
| 27 | + fn backtrace(&self) -> Option<&Backtrace> { |
| 28 | + self.inner.backtrace() |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl Display for MyError { |
| 33 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 34 | + Display::fmt(&self.inner, f) |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +To make the type easier to use, a few impls can be added: |
| 40 | + |
| 41 | +```rust |
| 42 | +// Allows writing `MyError::from("oops"))?` |
| 43 | +impl From<&'static str> for MyError { |
| 44 | + fn from(msg: &'static str) -> MyError { |
| 45 | + MyError { |
| 46 | + inner: Context::new(msg), |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// Allows adding more context via a String |
| 52 | +impl From<Context<String>> for MyError { |
| 53 | + fn from(inner: Context<String>) -> MyError { |
| 54 | + MyError { inner } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// Allows adding more context via a &str |
| 59 | +impl From<Context<&'static str>> for MyError { |
| 60 | + fn from(inner: Context<&'static str>) -> MyError { |
| 61 | + MyError { |
| 62 | + inner: inner.map(|s| s.to_string()), |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +Here is how it is used: |
| 69 | + |
| 70 | +```rust |
| 71 | +fn main() { |
| 72 | + println!("{:?}", err2()); |
| 73 | +} |
| 74 | + |
| 75 | +// Unlike the "Using the Error type" pattern, functions return our own error |
| 76 | +// type here. |
| 77 | +fn err1() -> Result<(), MyError> { |
| 78 | + Ok(Err(MyError::from("err1"))?) |
| 79 | +} |
| 80 | + |
| 81 | +fn err2() -> Result<(), MyError> { |
| 82 | + // Unlike the "An Error and ErrorKind pair" pattern, our context is a |
| 83 | + // simple string. We can chain errors and provide detailed error messages, |
| 84 | + // but we don't have to deal with the complexity of an error kind type |
| 85 | + Ok(err1().context("err2")?) |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +## Variant with `&'static str` |
| 90 | + |
| 91 | +If you don't need to format strings, you can avoid an |
| 92 | +allocation by using a `Context<&'static str>` instead of a |
| 93 | +`Context<String>`. |
| 94 | + |
| 95 | +```rust |
| 96 | +extern crate core; |
| 97 | +extern crate failure; |
| 98 | + |
| 99 | +use core::fmt::{self, Display}; |
| 100 | +use failure::{Backtrace, Context, Fail, ResultExt}; |
| 101 | + |
| 102 | +#[derive(Debug)] |
| 103 | +pub struct MyError { |
| 104 | + inner: Context<&'static str>, |
| 105 | +} |
| 106 | + |
| 107 | +impl Fail for MyError { |
| 108 | + fn cause(&self) -> Option<&Fail> { |
| 109 | + self.inner.cause() |
| 110 | + } |
| 111 | + |
| 112 | + fn backtrace(&self) -> Option<&Backtrace> { |
| 113 | + self.inner.backtrace() |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +impl Display for MyError { |
| 118 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 119 | + Display::fmt(&self.inner, f) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +impl From<&'static str> for MyError { |
| 124 | + fn from(msg: &'static str) -> MyError { |
| 125 | + MyError { |
| 126 | + inner: Context::new(msg.into()), |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +impl From<Context<&'static str>> for MyError { |
| 132 | + fn from(inner: Context<&'static str>) -> MyError { |
| 133 | + MyError { |
| 134 | + inner, |
| 135 | + } |
| 136 | + } |
| 137 | +} |
| 138 | +``` |
| 139 | + |
| 140 | +## When might you use this pattern? |
| 141 | + |
| 142 | +Sometimes, you don't want to use the [_Using the Error type_](./use-error.md) |
| 143 | +pattern, because you want to expose a few different error types. But you don't |
| 144 | +want to use the [_An Error and ErrorKind pair_](./error-errorkind.md) pattern |
| 145 | +either, because there is no need to provide the context as an enum or because |
| 146 | +it would be too much work, if the error can occur in many different contexts. |
| 147 | + |
| 148 | +For instance, if you're writing a library that decodes/encodes a complex binary |
| 149 | +format, you might want to expose a `DecodeError` and an `EncodeError` error |
| 150 | +type, but provide the context as a simple string instead of an error kind, because: |
| 151 | + |
| 152 | +- users may not care too much about the context in which a `DecodeError` or |
| 153 | + `EncodeError` was encountered, they just want a nice message to explain it |
| 154 | +- your binary format is really complex, errors can occur in many different |
| 155 | + places, and you don't want to end up with a giant `ErrorKind` enum |
| 156 | + |
| 157 | + |
| 158 | +## Caveats on this pattern |
| 159 | + |
| 160 | +If using the `Context<String>` variant, an extra allocation is used for the string. |
0 commit comments