Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily convert third party Errors to String

Tags:

rust

I have this code:

fn do_stuff() -> Result<i32, String> {

    let repo = git2::Repository::open(".")?;
    // ...
}

This doesn't work because git2::Repository::open()'s error type isn't String. (Yes I'm being pretty lazy with my error handling by using Strings. It's a tiny program; sue me.)

error[E0277]: the trait bound `std::string::String: std::convert::From<git2::Error>` is not satisfied
  --> src/main.rs:94:13
   |
94 |    let repo = Repository::open(".")?;
   |               ^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<git2::Error>` is not implemented for `std::string::String`
   |
   = help: the following implementations were found:
   = help:   <std::string::String as std::convert::From<&'a str>>
   = help:   <std::string::String as std::convert::From<std::borrow::Cow<'a, str>>>
   = note: required by `std::convert::From::from`

I've tried adding this:

impl std::convert::From<git2::Error> for String {
    fn from(err: git2::Error) -> Self {
        err.to_string()
    }
}

But that isn't allowed because it doesn't reference any types defined in this crate.

I know I can probably use .map_err(), but I'd really like it to happen automatically. I kind of feel like I have got this to work before too, which is a bit annoying!

like image 357
Timmmm Avatar asked Jan 30 '17 16:01

Timmmm


2 Answers

If a type implements std::error::Error, it also implements Display:

pub trait Error: Debug + Display {
    // ...
}

The ToString trait, which provides the method to_string, is implemented for any type that implements Display.

Thus, any type that implements Error can be converted to a String via to_string:

use git2; // 0.13.2

fn do_stuff() -> Result<i32, String> {
    let repo = git2::Repository::open(".").map_err(|e| e.to_string())?;
    unimplemented!()
}
like image 79
Shepmaster Avatar answered Oct 09 '22 20:10

Shepmaster


Well it turns out there is a bit in the Rust book about this. It doesn't allow you to convert to String, but apparently all Error types can be converted to Box<Error> so I just replaced String with that. It's cleaner too.

like image 43
Timmmm Avatar answered Oct 09 '22 19:10

Timmmm