I want to use my customised error type in all functions and I need to wrap the existing standard errors so that the ?
operator will succeed.
Here is what I am doing:
use std::{error::Error, fmt, fs};
#[derive(Debug)]
enum MyError {
A,
B,
}
impl fmt::Display for MyError {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
impl Error for MyError {
fn description(&self) -> &str {
""
}
}
trait NotMyError {}
impl<T: NotMyError + Error> From<T> for MyError {
fn from(_: T) -> MyError {
MyError::A
}
}
fn test() -> Result<(), MyError> {
fs::read_dir("test")?;
Ok(())
}
fn main() {}
The compiler complains:
error[E0277]: the trait bound `std::io::Error: NotMyError` is not satisfied
--> src/main.rs:30:5
|
30 | fs::read_dir("test")?;
| ^^^^^^^^^^^^^^^^^^^^^ the trait `NotMyError` is not implemented for `std::io::Error`
|
= note: required because of the requirements on the impl of `std::convert::From<std::io::Error>` for `MyError`
= note: required by `std::convert::From::from`
std::error::Error + Send + Sync
(which probably doesn’t implementError
, so that part is true) comes in—theT
in theFrom
implementation isstd::io::error::Error
.std::io::error::Error
contains a boxedError + Send + Sync
, but that shouldn’t have any impact here.Send
andSync
and so it interacts poorly with trait objects; the typestd::error::Error
, for example, doesn’t implementSend
, whilestd::error::Error + Send
does. Using the negative implementations approach means that anything that contains a trait object that doesn’t have theNotMyError
bound added (e.g.std::error::Error + Send + Sync + NotMyError
) doesn’t implementNotMyError
. So sorry, this approach I fed you earlier seems like it really won’t work.impl error::Error for ParseClimateError {}