The official Rust book, The Rust Programming Language, is freely available online. It has an entire chapter on using Result
, explaining introductory topics such as the Result
enum and how to use it.
How to return a Result
containing a serde_json::Value
?
The same way you return a Result
of any type; there's nothing special about Value
:
use serde_json::json; // 1.0.38
pub fn ok_example() -> Result<serde_json::value::Value, i32> {
Ok(json! { "success" })
}
pub fn err_example() -> Result<serde_json::value::Value, i32> {
Err(42)
}
If you have a function that returns a Result
, you can use the question mark operator (?
) to exit early from a function on error, returning the error. This is a concise way to avoid unwrap
or expect
:
fn use_them() -> Result<(), i32> {
let ok = ok_example()?;
println!("{:?}", ok);
let err = err_example()?;
println!("{:?}", err); // Never executed, we always exit due to the `?`
Ok(()) // Never executed
}
This is just a basic example.
Applied to your MCVE, it would look something like:
use reqwest; // 0.9.10
use serde_json::Value; // 1.0.38
type Error = Box<dyn std::error::Error>;
pub fn perform_get(_id: String) -> Result<Value, Error> {
let client = reqwest::Client::builder().build()?;
let url = String::from("SomeURL");
let res = client.get(&url).send()?.text()?;
let v = serde_json::from_str(&res)?;
Ok(v)
}
Here, I'm using the trait object Box<dyn std::error::Error>
to handle any kind of error (great for quick programs and examples). I then sprinkle ?
on every method that could fail (i.e. returns a Result
) and end the function with an explicit Ok
for the final value.
Note that the panic
and the never-used null
value can be removed with this style.
See also:
better practice to return a Result
See also: