Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How errors should be treated implementing fmt::Display?

I wonder how to convert properly interim errors of other types than fmt::Error which may arise on the track of fn fmt, to the fmt::Error type?

Let's say:

use std::fmt;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct MyStruct {
    x: i32
}

impl fmt::Display for MyStruct {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(&self).map_err(|e| /*???*/)?)
    }
}

As shown in the example above, I wonder how should I convert, for instance, serde_json::Error to fmt::Error to comply with the returned fmt::Result trait.

like image 752
dronte7 Avatar asked Oct 16 '25 15:10

dronte7


1 Answers

fmt::Error has no fields. It's simply an indicator value that "does not support transmission of an error other than that an error occurred" (docs). So, if you're fine with just returning an error with no other message, then map the error to fmt::Error:

foo.map_err(|_| fmt::Error)
like image 67
Aplet123 Avatar answered Oct 18 '25 08:10

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!