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
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.
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 .
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.
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