Error handling examples

This commit is contained in:
Timothy Warren 2019-01-30 16:27:06 -05:00
parent 124e78131a
commit 17f7e4dfcf
6 changed files with 128 additions and 21 deletions

2
.gitignore vendored
View File

@ -42,3 +42,5 @@ Cargo.lock
**/*.rs.bk
# End of https://www.gitignore.io/api/osx,rust
errors/hello.txt

1
.idea/misc.xml generated
View File

@ -15,6 +15,7 @@
<cargoProject FILE="$PROJECT_DIR$/rectangles/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/enums/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/modules/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/errors/Cargo.toml" />
</component>
<component name="ComposerJsonPluginSettings">
<unboundedVersionInspectionSettings>

5
.idea/rust.iml generated
View File

@ -59,9 +59,14 @@
<sourceFolder url="file://$MODULE_DIR$/modules/examples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/modules/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/modules/benches" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/errors/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/errors/examples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/errors/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/errors/benches" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/branches/target" />
<excludeFolder url="file://$MODULE_DIR$/ctof/target" />
<excludeFolder url="file://$MODULE_DIR$/enums/target" />
<excludeFolder url="file://$MODULE_DIR$/errors/target" />
<excludeFolder url="file://$MODULE_DIR$/ftoc/target" />
<excludeFolder url="file://$MODULE_DIR$/functions/target" />
<excludeFolder url="file://$MODULE_DIR$/guessing_game/target" />

69
.idea/workspace.xml generated
View File

@ -3,6 +3,9 @@
<component name="ChangeListManager">
<list default="true" id="c8f42924-1cd2-4b1c-bcff-602a3368bb16" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/.gitignore" beforeDir="false" afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/rust.iml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/rust.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
</list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
@ -13,10 +16,14 @@
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/guessing_game/.gitignore">
<entry file="file://$PROJECT_DIR$/errors/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="32">
<caret line="2" column="5" selection-start-line="2" selection-start-column="5" selection-end-line="2" selection-end-column="5" />
<state relative-caret-position="1024">
<caret line="64" column="1" lean-forward="true" selection-start-line="64" selection-start-column="1" selection-end-line="64" selection-end-column="1" />
<folding>
<element signature="e#285#286#0" expanded="true" />
<element signature="e#323#324#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
@ -24,8 +31,8 @@
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/.gitignore">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="544">
<caret line="34" column="12" selection-start-line="34" selection-start-column="12" selection-end-line="34" selection-end-column="12" />
<state relative-caret-position="720">
<caret line="45" column="16" selection-start-line="45" selection-start-column="16" selection-end-line="45" selection-end-column="16" />
</state>
</provider>
</entry>
@ -70,6 +77,7 @@
<option value="$PROJECT_DIR$/modules/src/main.rs" />
<option value="$PROJECT_DIR$/modules/src/sound/instrument.rs" />
<option value="$PROJECT_DIR$/guessing_game/.gitignore" />
<option value="$PROJECT_DIR$/errors/src/main.rs" />
<option value="$PROJECT_DIR$/.gitignore" />
</list>
</option>
@ -101,6 +109,11 @@
<item name="rust" type="3d21c010:ScopeViewTreeModel$ProjectNode" />
<item name="rust" type="2674bda8:ScopeViewTreeModel$GroupNode" />
</path>
<path>
<item name="rust" type="3d21c010:ScopeViewTreeModel$ProjectNode" />
<item name="rust" type="2674bda8:ScopeViewTreeModel$GroupNode" />
<item name="errors" type="9f88c78c:ScopeViewTreeModel$FileNode" />
</path>
</expand>
<select />
</subPane>
@ -132,7 +145,7 @@
</component>
<component name="PropertiesComponent">
<property name="JavaScriptWeakerCompletionTypeGuess" value="true" />
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1548879647202" />
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1548883606455" />
<property name="javascript.nodejs.core.library.configured.version" value="7.1.0" />
<property name="js.eslint.eslintPackage" value="$USER_HOME$/.yarn-config/global/node_modules/.bin/eslint" />
<property name="js.eslint.nodeInterpreter" value="project" />
@ -160,7 +173,7 @@
</list>
</option>
</component>
<component name="RunManager" selected="Cargo Command.Run modules">
<component name="RunManager" selected="Cargo Command.Run errors">
<configuration name="&lt;template&gt;" type="TestNG" default="true" selected="false">
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" value="-ea" />
@ -189,6 +202,16 @@
<envs />
<method v="2" />
</configuration>
<configuration name="Run errors" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package errors --bin errors" />
<option name="allFeatures" value="false" />
<option name="nocapture" value="false" />
<option name="backtrace" value="SHORT" />
<option name="workingDirectory" value="file://$PROJECT_DIR$/errors" />
<envs />
<method v="2" />
</configuration>
<configuration name="Run modules" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package modules --bin modules" />
@ -209,16 +232,6 @@
<envs />
<method v="2" />
</configuration>
<configuration name="Run slices" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package slices --bin slices" />
<option name="allFeatures" value="false" />
<option name="nocapture" value="false" />
<option name="backtrace" value="SHORT" />
<option name="workingDirectory" value="file://$PROJECT_DIR$/slices" />
<envs />
<method v="2" />
</configuration>
<configuration name="Run structs" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package structs --bin structs" />
@ -238,11 +251,11 @@
</configuration>
<recent_temporary>
<list>
<item itemvalue="Cargo Command.Run errors" />
<item itemvalue="Cargo Command.Run modules" />
<item itemvalue="Cargo Command.Run enums" />
<item itemvalue="Cargo Command.Run rectangles" />
<item itemvalue="Cargo Command.Run structs" />
<item itemvalue="Cargo Command.Run slices" />
</list>
</recent_temporary>
</component>
@ -258,7 +271,7 @@
<window_info id="Favorites" order="5" side_tool="true" />
<window_info id="Cargo" order="6" sideWeight="0.49791494" weight="0.3286119" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" />
<window_info anchor="bottom" id="Find" order="1" weight="0.32979318" />
<window_info anchor="bottom" id="Run" order="2" visible="true" weight="0.32979318" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
@ -438,10 +451,24 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/errors/hello.txt">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/errors/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1024">
<caret line="64" column="1" lean-forward="true" selection-start-line="64" selection-start-column="1" selection-end-line="64" selection-end-column="1" />
<folding>
<element signature="e#285#286#0" expanded="true" />
<element signature="e#323#324#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/.gitignore">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="544">
<caret line="34" column="12" selection-start-line="34" selection-start-column="12" selection-end-line="34" selection-end-column="12" />
<state relative-caret-position="720">
<caret line="45" column="16" selection-start-line="45" selection-start-column="16" selection-end-line="45" selection-end-column="16" />
</state>
</provider>
</entry>

7
errors/Cargo.toml Normal file
View File

@ -0,0 +1,7 @@
[package]
name = "errors"
version = "0.1.0"
authors = ["Timothy Warren <twarren@nabancard.com>"]
edition = "2018"
[dependencies]

65
errors/src/main.rs Normal file
View File

@ -0,0 +1,65 @@
use std::fs;
use std::fs::File;
use std::io::{Error, ErrorKind, Read};
fn main() {
let _str = handle_errors_with_match();
let _str = match handle_errors_with_closures() {
Ok(_) => println!("Opened or created the file successfully!"),
Err(e) => panic!("There was a problem opening the file: {:?}", e),
};
let _str = match read_username_from_file() {
Ok(_) => println!("Opened or created the file successfully!"),
Err(e) => panic!("There was a problem opening the file: {:?}", e),
};
let _str = match easy_mode() {
Ok(_) => println!("Opened or created the file successfully!"),
Err(e) => panic!("There was a problem opening the file: {:?}", e),
};
}
fn easy_mode() -> Result<String, Error> {
fs::read_to_string("hello.txt")
}
fn read_username_from_file() -> Result<String, Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
fn handle_errors_with_closures () -> Result<File, File> {
File::open("hello.txt").map_err(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Tried to create file but there was a problem: {:?}", error);
})
} else {
panic!("There was a problem opening the file: {:?}", error);
}
})
}
fn handle_errors_with_match () -> File {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Tried to create file but there was a problem: {:?}", e),
},
other_error => panic!("There was a problem opening the file: {:?}", other_error),
},
};
println!("Opened or created the file successfully!");
f
}