Pattern matching over different types of errors


#1

I have something like this:

extern crate slurp;
use std::process;

fn main() {
    for line in slurp::iterate_all_lines("somefile") {
        match line {
            Err(e) => {
                println!("{:?}", e);
                process::exit(0x01)
            },
            Ok(l) => println!("{}", l)
        }
    }
}

If I have no access to the file I get this error:

Os { code: 13, kind: PermissionDenied, message: "Permission denied" }

If there is a problem with the encoding I get:

Custom { kind: InvalidData, error: StringError("stream did not contain valid UTF-8") }

Now I would like to distinguish between Os{…} and Custom{…} errors. Though, I don’t know actually if there are other types of errors.

I have no idea how to achieve this. Any help appreciated.


#2

You can’t match on std::io::Error. You can however call .kind() to get the ErrorKind and match on that. Also, you can call .raw_os_error(), which will be Some if it was an OS error. For more information, see the std::io::Error documentation.


#3

Thanks for your reply. I changed it like follows which works fine.

extern crate slurp;
use std::process;

fn main() {
    for line in slurp::iterate_all_lines("somefile") {
        match line {
            Err(e) => match e.kind() {
                std::io::ErrorKind::InvalidData => println!("Error: {}", e),
                std::io::ErrorKind::PermissionDenied => {
                    println!("Error: {}", e);
                    process::exit(0x01)
                },
                _ => {
                    println!("Error: {}",e);
                    process::exit(0x02)
                }
            },
            Ok(l) => println!("{}", l)
        }
    }
}