Skip to content

Commit 62f0ea7

Browse files
committed
Add documentation for contexts
1 parent d7d01f9 commit 62f0ea7

File tree

1 file changed

+57
-4
lines changed

1 file changed

+57
-4
lines changed

src/lib.rs

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -197,10 +197,63 @@
197197
//! }
198198
//! ```
199199
//!
200-
//! All forms of `from`, `display`, `description`, `cause` clauses can be
201-
//! combined and put in arbitrary order. Only `from` may be used multiple times
202-
//! in single variant of enumeration. Docstrings are also okay.
203-
//! Empty braces can be omitted as of quick_error 0.1.3.
200+
//! Since quick-error 1.1 we also have a `context` declaration, which is
201+
//! similar to (the longest form of) `from`, but allows adding some context to
202+
//! the error. We need a longer example to demonstrate this:
203+
//!
204+
//! ```rust
205+
//! # #[macro_use] extern crate quick_error;
206+
//! # use std::io;
207+
//! # use std::fs::File;
208+
//! # use std::path::{Path, PathBuf};
209+
//! #
210+
//! use quick_error::ResultExt;
211+
//!
212+
//! quick_error! {
213+
//! #[derive(Debug)]
214+
//! pub enum Error {
215+
//! File(filename: PathBuf, err: io::Error) {
216+
//! context(path: &'a Path, err: io::Error)
217+
//! -> (path.to_path_buf(), err)
218+
//! }
219+
//! }
220+
//! }
221+
//!
222+
//! fn openfile(path: &Path) -> Result<(), Error> {
223+
//! try!(File::open(path).context(path));
224+
//!
225+
//! // If we didn't have context, the line above would be written as;
226+
//! //
227+
//! // try!(File::open(path)
228+
//! // .map_err(|err| Error::File(path.to_path_buf(), err)));
229+
//!
230+
//! Ok(())
231+
//! }
232+
//!
233+
//! # fn main() {
234+
//! # openfile(Path::new("/etc/somefile")).ok();
235+
//! # }
236+
//! ```
237+
//!
238+
//! Each `context(a: A, b: B)` clause implements
239+
//! `From<Context<A, B>> for Error`. Which means multiple `context` clauses
240+
//! are a subject to the normal coherence rules. Unfortunately, we can't
241+
//! provide full support of generics for the context, but you may either use a
242+
//! lifetime `'a` for references or `AsRef<Type>` (the latter means `A:
243+
//! AsRef<Type>`, and `Type` must be concrete). It's also occasionally useful
244+
//! to use a tuple as a type of the first argument.
245+
//!
246+
//! You also need to `use quick_error::ResultExt` extension trait to get
247+
//! working `.context()` method.
248+
//!
249+
//! More info on context in [this article](http://bit.ly/1PsuxDt).
250+
//!
251+
//! All forms of `from`, `display`, `description`, `cause`, and `context`
252+
//! clauses can be combined and put in arbitrary order. Only `from` and
253+
//! `context` can be used multiple times in single variant of enumeration.
254+
//! Docstrings are also okay. Empty braces can be omitted as of quick_error
255+
//! 0.1.3.
256+
//!
204257
//!
205258
206259

0 commit comments

Comments
 (0)