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`
It does not matter that the error is wrapped. A simple comparison if err == ErrorInternal would give false in this case, so it is generally a better idea to use the errors.Is() function to compare errors equality. Then, we unwrap the error using the errors. Unwrap() and print it to the standard output.
The easiest way to create custom errors in Golang is to use the New() function which is present in the errors module of Golang.
error is a built-in interface type in Go. An error variable represents any value that can describe itself as a string . The interface consists of a single function, Error() , that returns a string error message.
There's an excellent post about it. To get first-class support for your error you need to do two things:
Error
trait for your type.std::convert::From
for error types you want to use seamlessly with the ?
operator (the quick_error crate helps automate this).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With