Skip to content

Commit 5e17cbc

Browse files
committed
Add documentation
1 parent 27fcd5b commit 5e17cbc

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/lib.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,53 @@
1-
// #![deny(missing_docs)]
1+
//! This crate provides the [`context`](attr.context.html) macro for adding extra error
2+
//! information to a function.
3+
//!
4+
//! Works with [`anyhow`], [`failure`] and any other error type which
5+
//! provides a `context` method taking a string.
6+
//!
7+
//! ```
8+
//! # use std::fs::read_to_string;
9+
//! # use std::path::Path;
10+
//! #
11+
//! use fn_error_context::context;
12+
//!
13+
//! #[context("failed to parse config at `{}`", path.as_ref().display())]
14+
//! pub fn parse_config(path: impl AsRef<Path>) -> anyhow::Result<u32> {
15+
//! let text = read_to_string(path.as_ref())?;
16+
//! Ok(text.parse()?)
17+
//! }
18+
//!
19+
//! assert_eq!(
20+
//! parse_config("not-found").unwrap_err().to_string(),
21+
//! "failed to parse config at `not-found`"
22+
//! );
23+
//! ```
24+
//!
25+
//! [`anyhow`]: https://crates.io/crates/anyhow
26+
//! [`failure`]: https://crates.io/crates/failure
27+
28+
#![deny(missing_docs)]
229

330
extern crate proc_macro;
431

532
use proc_macro::TokenStream;
633
use quote::quote;
734

35+
/// Add context to errors from a function.
36+
///
37+
/// The arguments to this macro are a format string with arguments using
38+
/// the standard `std::fmt` syntax. Arguments to the function can be used
39+
/// as long as they are not consumed in the function body.
40+
///
41+
/// This macro desugars to something like
42+
/// ```
43+
/// # fn function_body() {}
44+
/// #
45+
/// pub fn function() -> anyhow::Result<()> {
46+
/// (|| -> anyhow::Result<()> {
47+
/// function_body()
48+
/// })().map_err(|err| err.context("context"))
49+
/// }
50+
/// ```
851
#[proc_macro_attribute]
952
pub fn context(args: TokenStream, input: TokenStream) -> TokenStream {
1053
let args: proc_macro2::TokenStream = args.into();

0 commit comments

Comments
 (0)