|
| 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