2

I am attempting to return an error from Serde with a function that returns Result<(), Error>:

use std::io::{Error};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Mine {
    ab: u8,
    ac: u8,
}
#[macro_use]
extern crate serde_derive;

fn main() {
    if do_match().is_ok() {
        println!("Success");
    }
}

fn do_match() -> Result<(), Error> {
    match serde_json::from_str::<Mine>("test") {
        Ok(_e) => println!("Okay"),
        Err(e) => return e,
    }
    Ok(())
}

Rust Playground

After various attempts, I have been unable to correct the problem to return an error, how can I do this?

sshashank124
  • 31,495
  • 9
  • 67
  • 76
STF_ZBR
  • 617
  • 1
  • 4
  • 19

1 Answers1

3

Firstly, you are using the wrong error type. serde_json::from_str's Err is of type serde_json::error::Error whereas you are using std::io::Error. Secondly, by pattern matching on Err(e) and then trying to return e, you are no longer return a Result but instead trying to just return something of type serde_json::error::Error. Instead, you should be returning Result<(), serde_json::error::Error>. Here is the proper way to accomplish what you are trying to achieve:

fn do_match() -> Result <(), serde_json::error::Error> {
    serde_json::from_str::<Mine>("test").map(|_| println!("Okay"))
}

map will only perform the println!(...) on the result from serde_json::from_str if it is an Ok variant, otherwise, it will just pass through the Err variant. Then, you can just return the resulting expression.

Rust Playground

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • Is there any reason to not implement `std::error::Error` for `serde_json::error::Error`? As a framework developer it can be challenging to handle disparate Error types from Results – ThisCompSciGuy Mar 09 '23 at 18:51