Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an error wrapper for all existing Errors?

Tags:

rust

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`
like image 939
Amos Avatar asked Apr 30 '15 04:04

Amos


People also ask

How do you wrap an error in go?

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.

How do you create an error variable in Golang?

The easiest way to create custom errors in Golang is to use the New() function which is present in the errors module of Golang.

What is the type of error in 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.


1 Answers

There's an excellent post about it. To get first-class support for your error you need to do two things:

  • Implement the Error trait for your type.
  • Implement std::convert::From for error types you want to use seamlessly with the ? operator (the quick_error crate helps automate this).
like image 58
Kornel Avatar answered Sep 24 '22 02:09

Kornel