Skip to content

Commit f3e0acc

Browse files
committed
Add helper traits/macros to produce FieldResults
1 parent 3b71755 commit f3e0acc

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ mod schema;
193193
mod validation;
194194
mod executor;
195195
mod integrations;
196+
#[macro_use] mod result_ext;
196197

197198
#[cfg(all(test, not(feature="expose-test-schema")))] mod tests;
198199
#[cfg(feature="expose-test-schema")] pub mod tests;
@@ -216,6 +217,7 @@ pub use executor::{
216217
pub use validation::RuleError;
217218
pub use types::scalars::ID;
218219
pub use schema::model::RootNode;
220+
pub use result_ext::ResultExt;
219221

220222
pub use schema::meta;
221223

src/result_ext.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
use std::fmt;
2+
use std::result::Result;
3+
4+
/**
5+
Helper trait to produce `FieldResult`s
6+
7+
`FieldResult` only have strings as errors as that's what's going out
8+
in the GraphQL response. As such, all errors must be manually
9+
converted to strings. Importing the `ResultExt` macro and using its
10+
only method `to_field_err` can help with that:
11+
12+
```rust
13+
use std::str::FromStr;
14+
use juniper::{FieldResult, ResultExt};
15+
16+
fn sample_fn(s: &str) -> FieldResult<i64> {
17+
i64::from_str(s).to_field_err()
18+
}
19+
20+
# fn main() { assert_eq!(sample_fn("12"), Ok(12)); }
21+
```
22+
23+
Alternatively, you can use the `jtry!` macro in all places you'd
24+
normally use the regular `try!` macro:
25+
26+
```rust
27+
#[macro_use] extern crate juniper;
28+
29+
use std::str::FromStr;
30+
31+
use juniper::{FieldResult, ResultExt};
32+
33+
fn sample_fn(s: &str) -> FieldResult<i64> {
34+
let value = jtry!(i64::from_str(s));
35+
36+
Ok(value)
37+
}
38+
39+
# fn main() { assert_eq!(sample_fn("12"), Ok(12)); }
40+
```
41+
42+
*/
43+
pub trait ResultExt<T, E: fmt::Display> {
44+
/// Convert the error to a string by using it's `Display` implementation
45+
fn to_field_err(self) -> Result<T, String>;
46+
}
47+
48+
impl<T, E: fmt::Display> ResultExt<T, E> for Result<T, E> {
49+
fn to_field_err(self) -> Result<T, String> {
50+
self.map_err(|e| format!("{}", e))
51+
}
52+
}
53+
54+
/**
55+
Helper macro to produce `FieldResult`s.
56+
57+
See the documentation for the [`ResultExt`](trait.ResultExt.html)
58+
trait.
59+
*/
60+
#[macro_export]
61+
macro_rules! jtry {
62+
( $e:expr ) => { try!($crate::ResultExt::to_field_err($e)) }
63+
}

0 commit comments

Comments
 (0)