|
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)] |
2 | 29 |
|
3 | 30 | extern crate proc_macro;
|
4 | 31 |
|
5 | 32 | use proc_macro::TokenStream;
|
6 | 33 | use quote::quote;
|
7 | 34 |
|
| 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 | +/// ``` |
8 | 51 | #[proc_macro_attribute]
|
9 | 52 | pub fn context(args: TokenStream, input: TokenStream) -> TokenStream {
|
10 | 53 | let args: proc_macro2::TokenStream = args.into();
|
|
0 commit comments