Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the message string from std::io::Error?

Tags:

rust

This works:

format!("{:?}", error)) 
// Os { code: 13, kind: PermissionDenied, message: "Permission denied" }

But I want only the message field, not the full debug print. How do I get it?

error.message // unknown field
error.message() // no method named `message` found for type `std::io::Error` in the current scope
like image 671
Oleg Antonyan Avatar asked Mar 17 '18 16:03

Oleg Antonyan


People also ask

What does result () mean rust?

Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T) , representing success and containing a value, and Err(E) , representing error and containing an error value.

What is io result?

Type Definition std::io::ResultA specialized Result type for I/O operations. This type is broadly used across std::io for any operation which may produce an error. This typedef is generally used to avoid writing out io::Error directly and is otherwise a direct mapping to Result .


1 Answers

I don't think there's anything that will get you exactly "Permission denied". The closest I know of is the Display implementation of the Error, which still includes the underlying error code:

use std::fs::File;
use std::error::Error;

fn main() {
    let error = File::open("/does-not-exist").unwrap_err();

    println!("{:?}", error);
    // Error { repr: Os { code: 2, message: "No such file or directory" } }

    println!("{}", error);
    // No such file or directory (os error 2)

    println!("{}", error.description());
    // entity not found
}

If this is suitable, you can use error.to_string().


The standard library gets this string from sys::os, which gets defined based on the platform. For example, on UNIX-like platforms, it uses strerror_r. This function does not appear to be exposed in any public fashion, however.

like image 105
Shepmaster Avatar answered Nov 15 '22 07:11

Shepmaster