Last active
April 14, 2021 13:41
-
-
Save kahunacohen/6eb8311bfdf0edaa26839cae8ac7a5d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An example of how we can do error handling in rust. | |
*/ | |
use std::fmt; | |
use std::fs::File; | |
use std::io; | |
use std::result::Result; | |
// A custom Error type that has one variant, "Io" representing issues | |
// with reading from the config file. | |
#[derive(Debug)] | |
enum ConfigError { | |
Io(io::Error), | |
} | |
// Tell rust how to convert an IoError to a ConfigError. | |
// Essentially, take the original IOError and wrap it with the ConfigError. | |
impl From<io::Error> for ConfigError { | |
fn from(error: io::Error) -> Self { | |
ConfigError::Io(error) | |
} | |
} | |
// Tell rust how to print the ConfigError. For an IO variant, give the | |
// caller some context that it's config error, that it happenen when trying | |
// to load the file and print out the original error. | |
impl fmt::Display for ConfigError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match *self { | |
ConfigError::Io(ref e) => | |
write!(f, "configuration error: problem loading file: {}", e), | |
} | |
} | |
} | |
// Pretend we are getting a config from a file. | |
fn get_config() -> Result<File, ConfigError> { | |
let f = File::open("foobar")?; | |
Ok(f) | |
} | |
fn main() { | |
match get_config() { | |
Ok(f) => println!("{:?}", f), | |
Err(why) => println!("{}", why), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment