mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:24:32 -06:00
2099 lines
108 KiB
HTML
2099 lines
108 KiB
HTML
<!DOCTYPE HTML>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>Error Handling - The Rust Programming Language</title>
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
<meta name="description" content="">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
<base href="">
|
|
|
|
<link rel="stylesheet" href="book.css">
|
|
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
|
|
|
<link rel="shortcut icon" href="favicon.png">
|
|
|
|
<!-- Font Awesome -->
|
|
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
|
|
|
<link rel="stylesheet" href="highlight.css">
|
|
<link rel="stylesheet" href="tomorrow-night.css">
|
|
|
|
<!-- MathJax -->
|
|
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
|
|
|
<!-- Fetch JQuery from CDN but have a local fallback -->
|
|
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
|
<script>
|
|
if (typeof jQuery == 'undefined') {
|
|
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
|
}
|
|
</script>
|
|
</head>
|
|
<body class="light">
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
<script type="text/javascript">
|
|
var theme = localStorage.getItem('theme');
|
|
if (theme == null) { theme = 'light'; }
|
|
$('body').removeClass().addClass(theme);
|
|
</script>
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
<script type="text/javascript">
|
|
var sidebar = localStorage.getItem('sidebar');
|
|
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
|
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
|
</script>
|
|
|
|
<div id="sidebar" class="sidebar">
|
|
<ul class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong>1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong>2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong>3.</strong> Syntax and Semantics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> if</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong>3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong>3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong>3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong>3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong>3.12.</strong> Structs</a></li><li><a href="enums.html"><strong>3.13.</strong> Enums</a></li><li><a href="match.html"><strong>3.14.</strong> Match</a></li><li><a href="patterns.html"><strong>3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong>3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong>3.17.</strong> Strings</a></li><li><a href="generics.html"><strong>3.18.</strong> Generics</a></li><li><a href="traits.html"><strong>3.19.</strong> Traits</a></li><li><a href="drop.html"><strong>3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong>3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong>3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong>3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong>3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong>3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong>3.26.</strong> <code>const</code> and <code>static</code></a></li><li><a href="attributes.html"><strong>3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong>3.28.</strong> <code>type</code> aliases</a></li><li><a href="casting-between-types.html"><strong>3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong>3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong>3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong>3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong>3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong>3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong>3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong>3.36.</strong> <code>unsafe</code></a></li></ul></li><li><a href="effective-rust.html"><strong>4.</strong> Effective Rust</a></li><li><ul class="section"><li><a href="the-stack-and-the-heap.html"><strong>4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong>4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong>4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong>4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong>4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong>4.6.</strong> Concurrency</a></li><li><a href="error-handling.html" class="active"><strong>4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong>4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong>4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong>4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong>4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong>4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong>4.13.</strong> Procedural Macros (and custom derive)</a></li></ul></li><li><a href="glossary.html"><strong>5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong>6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong>7.</strong> Bibliography</a></li></ul>
|
|
</div>
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
<div class="page">
|
|
<div id="menu-bar" class="menu-bar">
|
|
<div class="left-buttons">
|
|
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
|
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
|
</div>
|
|
|
|
<h1 class="menu-title">The Rust Programming Language</h1>
|
|
|
|
<div class="right-buttons">
|
|
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="content" class="content">
|
|
<a class="header" href="error-handling.html#error-handling" id="error-handling"><h1>Error Handling</h1></a>
|
|
<p>Like most programming languages, Rust encourages the programmer to handle
|
|
errors in a particular way. Generally speaking, error handling is divided into
|
|
two broad categories: exceptions and return values. Rust opts for return
|
|
values.</p>
|
|
<p>In this section, we intend to provide a comprehensive treatment of how to deal
|
|
with errors in Rust. More than that, we will attempt to introduce error handling
|
|
one piece at a time so that you'll come away with a solid working knowledge of
|
|
how everything fits together.</p>
|
|
<p>When done naïvely, error handling in Rust can be verbose and annoying. This
|
|
section will explore those stumbling blocks and demonstrate how to use the
|
|
standard library to make error handling concise and ergonomic.</p>
|
|
<a class="header" href="error-handling.html#table-of-contents" id="table-of-contents"><h1>Table of Contents</h1></a>
|
|
<p>This section is very long, mostly because we start at the very beginning with
|
|
sum types and combinators, and try to motivate the way Rust does error handling
|
|
incrementally. As such, programmers with experience in other expressive type
|
|
systems may want to jump around.</p>
|
|
<ul>
|
|
<li><a href="error-handling.html#the-basics">The Basics</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#unwrapping-explained">Unwrapping explained</a></li>
|
|
<li><a href="error-handling.html#the-option-type">The <code>Option</code> type</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#composing-optiont-values">Composing <code>Option<T></code> values</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#the-result-type">The <code>Result</code> type</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#parsing-integers">Parsing integers</a></li>
|
|
<li><a href="error-handling.html#the-result-type-alias-idiom">The <code>Result</code> type alias idiom</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#a-brief-interlude-unwrapping-isnt-evil">A brief interlude: unwrapping isn't evil</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#working-with-multiple-error-types">Working with multiple error types</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#composing-option-and-result">Composing <code>Option</code> and <code>Result</code></a></li>
|
|
<li><a href="error-handling.html#the-limits-of-combinators">The limits of combinators</a></li>
|
|
<li><a href="error-handling.html#early-returns">Early returns</a></li>
|
|
<li><a href="error-handling.html#the-try-macro">The <code>try!</code> macro</a></li>
|
|
<li><a href="error-handling.html#defining-your-own-error-type">Defining your own error type</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#standard-library-traits-used-for-error-handling">Standard library traits used for error handling</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#the-error-trait">The <code>Error</code> trait</a></li>
|
|
<li><a href="error-handling.html#the-from-trait">The <code>From</code> trait</a></li>
|
|
<li><a href="error-handling.html#the-real-try-macro">The real <code>try!</code> macro</a></li>
|
|
<li><a href="error-handling.html#composing-custom-error-types">Composing custom error types</a></li>
|
|
<li><a href="error-handling.html#advice-for-library-writers">Advice for library writers</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#case-study-a-program-to-read-population-data">Case study: A program to read population data</a>
|
|
<ul>
|
|
<li><a href="error-handling.html#initial-setup">Initial setup</a></li>
|
|
<li><a href="error-handling.html#argument-parsing">Argument parsing</a></li>
|
|
<li><a href="error-handling.html#writing-the-logic">Writing the logic</a></li>
|
|
<li><a href="error-handling.html#error-handling-with-boxerror">Error handling with <code>Box<Error></code></a></li>
|
|
<li><a href="error-handling.html#reading-from-stdin">Reading from stdin</a></li>
|
|
<li><a href="error-handling.html#error-handling-with-a-custom-type">Error handling with a custom type</a></li>
|
|
<li><a href="error-handling.html#adding-functionality">Adding functionality</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="error-handling.html#the-short-story">The short story</a></li>
|
|
</ul>
|
|
<a class="header" href="error-handling.html#the-basics" id="the-basics"><h1>The Basics</h1></a>
|
|
<p>You can think of error handling as using <em>case analysis</em> to determine whether
|
|
a computation was successful or not. As you will see, the key to ergonomic error
|
|
handling is reducing the amount of explicit case analysis the programmer has to
|
|
do while keeping code composable.</p>
|
|
<p>Keeping code composable is important, because without that requirement, we
|
|
could <a href="../../std/macro.panic.html"><code>panic</code></a> whenever we
|
|
come across something unexpected. (<code>panic</code> causes the current task to unwind,
|
|
and in most cases, the entire program aborts.) Here's an example:</p>
|
|
<pre><pre class="playpen"><code class="language-rust should_panic">// Guess a number between 1 and 10.
|
|
// If it matches the number we had in mind, return `true`. Else, return `false`.
|
|
fn guess(n: i32) -> bool {
|
|
if n < 1 || n > 10 {
|
|
panic!("Invalid number: {}", n);
|
|
}
|
|
n == 5
|
|
}
|
|
|
|
fn main() {
|
|
guess(11);
|
|
}
|
|
</code></pre></pre>
|
|
<p>If you try running this code, the program will crash with a message like this:</p>
|
|
<pre><code class="language-text">thread 'main' panicked at 'Invalid number: 11', src/bin/panic-simple.rs:5
|
|
</code></pre>
|
|
<p>Here's another example that is slightly less contrived. A program that accepts
|
|
an integer as an argument, doubles it and prints it.</p>
|
|
<p><span id="code-unwrap-double"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust should_panic">use std::env;
|
|
|
|
fn main() {
|
|
let mut argv = env::args();
|
|
let arg: String = argv.nth(1).unwrap(); // error 1
|
|
let n: i32 = arg.parse().unwrap(); // error 2
|
|
println!("{}", 2 * n);
|
|
}
|
|
</code></pre></pre>
|
|
<p>If you give this program zero arguments (error 1) or if the first argument
|
|
isn't an integer (error 2), the program will panic just like in the first
|
|
example.</p>
|
|
<p>You can think of this style of error handling as similar to a bull running
|
|
through a china shop. The bull will get to where it wants to go, but it will
|
|
trample everything in the process.</p>
|
|
<a class="header" href="error-handling.html#unwrapping-explained" id="unwrapping-explained"><h2>Unwrapping explained</h2></a>
|
|
<p>In the previous example, we claimed
|
|
that the program would simply panic if it reached one of the two error
|
|
conditions, yet, the program does not include an explicit call to <code>panic</code> like
|
|
the first example. This is because the
|
|
panic is embedded in the calls to <code>unwrap</code>.</p>
|
|
<p>To “unwrap” something in Rust is to say, “Give me the result of the
|
|
computation, and if there was an error, panic and stop the program.”
|
|
It would be better if we showed the code for unwrapping because it is so
|
|
simple, but to do that, we will first need to explore the <code>Option</code> and <code>Result</code>
|
|
types. Both of these types have a method called <code>unwrap</code> defined on them.</p>
|
|
<a class="header" href="error-handling.html#the-option-type" id="the-option-type"><h3>The <code>Option</code> type</h3></a>
|
|
<p>The <code>Option</code> type is <a href="../../std/option/enum.Option.html">defined in the standard library</a>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
enum Option<T> {
|
|
None,
|
|
Some(T),
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>The <code>Option</code> type is a way to use Rust's type system to express the
|
|
<em>possibility of absence</em>. Encoding the possibility of absence into the type
|
|
system is an important concept because it will cause the compiler to force the
|
|
programmer to handle that absence. Let's take a look at an example that tries
|
|
to find a character in a string:</p>
|
|
<p><span id="code-option-ex-string-find"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
// Searches `haystack` for the Unicode character `needle`. If one is found, the
|
|
// byte offset of the character is returned. Otherwise, `None` is returned.
|
|
fn find(haystack: &str, needle: char) -> Option<usize> {
|
|
for (offset, c) in haystack.char_indices() {
|
|
if c == needle {
|
|
return Some(offset);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Notice that when this function finds a matching character, it doesn't only
|
|
return the <code>offset</code>. Instead, it returns <code>Some(offset)</code>. <code>Some</code> is a variant or
|
|
a <em>value constructor</em> for the <code>Option</code> type. You can think of it as a function
|
|
with the type <code>fn<T>(value: T) -> Option<T></code>. Correspondingly, <code>None</code> is also a
|
|
value constructor, except it has no arguments. You can think of <code>None</code> as a
|
|
function with the type <code>fn<T>() -> Option<T></code>.</p>
|
|
<p>This might seem like much ado about nothing, but this is only half of the
|
|
story. The other half is <em>using</em> the <code>find</code> function we've written. Let's try
|
|
to use it to find the extension in a file name.</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }
|
|
fn main() {
|
|
let file_name = "foobar.rs";
|
|
match find(file_name, '.') {
|
|
None => println!("No file extension found."),
|
|
Some(i) => println!("File extension: {}", &file_name[i+1..]),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>This code uses <a href="patterns.html">pattern matching</a> to do <em>case
|
|
analysis</em> on the <code>Option<usize></code> returned by the <code>find</code> function. In fact, case
|
|
analysis is the only way to get at the value stored inside an <code>Option<T></code>. This
|
|
means that you, as the programmer, must handle the case when an <code>Option<T></code> is
|
|
<code>None</code> instead of <code>Some(t)</code>.</p>
|
|
<p>But wait, what about <code>unwrap</code>, which we used <a href="error-handling.html#code-unwrap-double">previously</a>?
|
|
There was no case analysis there! Instead, the case analysis was put inside the
|
|
<code>unwrap</code> method for you. You could define it yourself if you want:</p>
|
|
<p><span id="code-option-def-unwrap"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
enum Option<T> {
|
|
None,
|
|
Some(T),
|
|
}
|
|
|
|
impl<T> Option<T> {
|
|
fn unwrap(self) -> T {
|
|
match self {
|
|
Option::Some(val) => val,
|
|
Option::None =>
|
|
panic!("called `Option::unwrap()` on a `None` value"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>The <code>unwrap</code> method <em>abstracts away the case analysis</em>. This is precisely the thing
|
|
that makes <code>unwrap</code> ergonomic to use. Unfortunately, that <code>panic!</code> means that
|
|
<code>unwrap</code> is not composable: it is the bull in the china shop.</p>
|
|
<a class="header" href="error-handling.html#composing-optiont-values" id="composing-optiont-values"><h3>Composing <code>Option<T></code> values</h3></a>
|
|
<p>In an <a href="error-handling.html#code-option-ex-string-find">example from before</a>,
|
|
we saw how to use <code>find</code> to discover the extension in a file name. Of course,
|
|
not all file names have a <code>.</code> in them, so it's possible that the file name has
|
|
no extension. This <em>possibility of absence</em> is encoded into the types using
|
|
<code>Option<T></code>. In other words, the compiler will force us to address the
|
|
possibility that an extension does not exist. In our case, we only print out a
|
|
message saying as such.</p>
|
|
<p>Getting the extension of a file name is a pretty common operation, so it makes
|
|
sense to put it into a function:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }
|
|
// Returns the extension of the given file name, where the extension is defined
|
|
// as all characters following the first `.`.
|
|
// If `file_name` has no `.`, then `None` is returned.
|
|
fn extension_explicit(file_name: &str) -> Option<&str> {
|
|
match find(file_name, '.') {
|
|
None => None,
|
|
Some(i) => Some(&file_name[i+1..]),
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>(Pro-tip: don't use this code. Use the
|
|
<a href="../../std/path/struct.Path.html#method.extension"><code>extension</code></a>
|
|
method in the standard library instead.)</p>
|
|
<p>The code stays simple, but the important thing to notice is that the type of
|
|
<code>find</code> forces us to consider the possibility of absence. This is a good thing
|
|
because it means the compiler won't let us accidentally forget about the case
|
|
where a file name doesn't have an extension. On the other hand, doing explicit
|
|
case analysis like we've done in <code>extension_explicit</code> every time can get a bit
|
|
tiresome.</p>
|
|
<p>In fact, the case analysis in <code>extension_explicit</code> follows a very common
|
|
pattern: <em>map</em> a function on to the value inside of an <code>Option<T></code>, unless the
|
|
option is <code>None</code>, in which case, return <code>None</code>.</p>
|
|
<p>Rust has parametric polymorphism, so it is very easy to define a combinator
|
|
that abstracts this pattern:</p>
|
|
<p><span id="code-option-map"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
fn map<F, T, A>(option: Option<T>, f: F) -> Option<A> where F: FnOnce(T) -> A {
|
|
match option {
|
|
None => None,
|
|
Some(value) => Some(f(value)),
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Indeed, <code>map</code> is <a href="../../std/option/enum.Option.html#method.map">defined as a method</a> on <code>Option<T></code> in the standard library.
|
|
As a method, it has a slightly different signature: methods take <code>self</code>, <code>&self</code>,
|
|
or <code>&mut self</code> as their first argument.</p>
|
|
<p>Armed with our new combinator, we can rewrite our <code>extension_explicit</code> method
|
|
to get rid of the case analysis:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# fn find(haystack: &str, needle: char) -> Option<usize> { haystack.find(needle) }
|
|
// Returns the extension of the given file name, where the extension is defined
|
|
// as all characters following the first `.`.
|
|
// If `file_name` has no `.`, then `None` is returned.
|
|
fn extension(file_name: &str) -> Option<&str> {
|
|
find(file_name, '.').map(|i| &file_name[i+1..])
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>One other pattern we commonly find is assigning a default value to the case
|
|
when an <code>Option</code> value is <code>None</code>. For example, maybe your program assumes that
|
|
the extension of a file is <code>rs</code> even if none is present. As you might imagine,
|
|
the case analysis for this is not specific to file extensions - it can work
|
|
with any <code>Option<T></code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
fn unwrap_or<T>(option: Option<T>, default: T) -> T {
|
|
match option {
|
|
None => default,
|
|
Some(value) => value,
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Like with <code>map</code> above, the standard library implementation is a method instead
|
|
of a free function.</p>
|
|
<p>The trick here is that the default value must have the same type as the value
|
|
that might be inside the <code>Option<T></code>. Using it is dead simple in our case:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># fn find(haystack: &str, needle: char) -> Option<usize> {
|
|
# for (offset, c) in haystack.char_indices() {
|
|
# if c == needle {
|
|
# return Some(offset);
|
|
# }
|
|
# }
|
|
# None
|
|
# }
|
|
#
|
|
# fn extension(file_name: &str) -> Option<&str> {
|
|
# find(file_name, '.').map(|i| &file_name[i+1..])
|
|
# }
|
|
fn main() {
|
|
assert_eq!(extension("foobar.csv").unwrap_or("rs"), "csv");
|
|
assert_eq!(extension("foobar").unwrap_or("rs"), "rs");
|
|
}
|
|
</code></pre></pre>
|
|
<p>(Note that <code>unwrap_or</code> is <a href="../../std/option/enum.Option.html#method.unwrap_or">defined as a method</a> on <code>Option<T></code> in the
|
|
standard library, so we use that here instead of the free-standing function we
|
|
defined above. Don't forget to check out the more general <a href="../../std/option/enum.Option.html#method.unwrap_or_else"><code>unwrap_or_else</code></a>
|
|
method.)</p>
|
|
<p>There is one more combinator that we think is worth paying special attention to:
|
|
<code>and_then</code>. It makes it easy to compose distinct computations that admit the
|
|
<em>possibility of absence</em>. For example, much of the code in this section is
|
|
about finding an extension given a file name. In order to do this, you first
|
|
need the file name which is typically extracted from a file <em>path</em>. While most
|
|
file paths have a file name, not <em>all</em> of them do. For example, <code>.</code>, <code>..</code> or
|
|
<code>/</code>.</p>
|
|
<p>So, we are tasked with the challenge of finding an extension given a file
|
|
<em>path</em>. Let's start with explicit case analysis:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# fn extension(file_name: &str) -> Option<&str> { None }
|
|
fn file_path_ext_explicit(file_path: &str) -> Option<&str> {
|
|
match file_name(file_path) {
|
|
None => None,
|
|
Some(name) => match extension(name) {
|
|
None => None,
|
|
Some(ext) => Some(ext),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn file_name(file_path: &str) -> Option<&str> {
|
|
// Implementation elided.
|
|
unimplemented!()
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>You might think that we could use the <code>map</code> combinator to reduce the case
|
|
analysis, but its type doesn't quite fit...</p>
|
|
<pre><code class="language-rust ignore">fn file_path_ext(file_path: &str) -> Option<&str> {
|
|
file_name(file_path).map(|x| extension(x)) // This causes a compilation error.
|
|
}
|
|
</code></pre>
|
|
<p>The <code>map</code> function here wraps the value returned by the <code>extension</code> function
|
|
inside an <code>Option<_></code> and since the <code>extension</code> function itself returns an
|
|
<code>Option<&str></code> the expression <code>file_name(file_path).map(|x| extension(x))</code>
|
|
actually returns an <code>Option<Option<&str>></code>.</p>
|
|
<p>But since <code>file_path_ext</code> just returns <code>Option<&str></code> (and not
|
|
<code>Option<Option<&str>></code>) we get a compilation error.</p>
|
|
<p>The result of the function taken by map as input is <em>always</em> <a href="error-handling.html#code-option-map">rewrapped with
|
|
<code>Some</code></a>. Instead, we need something like <code>map</code>, but which
|
|
allows the caller to return a <code>Option<_></code> directly without wrapping it in
|
|
another <code>Option<_></code>.</p>
|
|
<p>Its generic implementation is even simpler than <code>map</code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
fn and_then<F, T, A>(option: Option<T>, f: F) -> Option<A>
|
|
where F: FnOnce(T) -> Option<A> {
|
|
match option {
|
|
None => None,
|
|
Some(value) => f(value),
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Now we can rewrite our <code>file_path_ext</code> function without explicit case analysis:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# fn extension(file_name: &str) -> Option<&str> { None }
|
|
# fn file_name(file_path: &str) -> Option<&str> { None }
|
|
fn file_path_ext(file_path: &str) -> Option<&str> {
|
|
file_name(file_path).and_then(extension)
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Side note: Since <code>and_then</code> essentially works like <code>map</code> but returns an
|
|
<code>Option<_></code> instead of an <code>Option<Option<_>></code> it is known as <code>flatmap</code> in some
|
|
other languages.</p>
|
|
<p>The <code>Option</code> type has many other combinators <a href="../../std/option/enum.Option.html">defined in the standard
|
|
library</a>. It is a good idea to skim this list and familiarize
|
|
yourself with what's available—they can often reduce case analysis
|
|
for you. Familiarizing yourself with these combinators will pay
|
|
dividends because many of them are also defined (with similar
|
|
semantics) for <code>Result</code>, which we will talk about next.</p>
|
|
<p>Combinators make using types like <code>Option</code> ergonomic because they reduce
|
|
explicit case analysis. They are also composable because they permit the caller
|
|
to handle the possibility of absence in their own way. Methods like <code>unwrap</code>
|
|
remove choices because they will panic if <code>Option<T></code> is <code>None</code>.</p>
|
|
<a class="header" href="error-handling.html#the-result-type" id="the-result-type"><h2>The <code>Result</code> type</h2></a>
|
|
<p>The <code>Result</code> type is also
|
|
<a href="../../std/result/index.html">defined in the standard library</a>:</p>
|
|
<p><span id="code-result-def"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
enum Result<T, E> {
|
|
Ok(T),
|
|
Err(E),
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>The <code>Result</code> type is a richer version of <code>Option</code>. Instead of expressing the
|
|
possibility of <em>absence</em> like <code>Option</code> does, <code>Result</code> expresses the possibility
|
|
of <em>error</em>. Usually, the <em>error</em> is used to explain why the execution of some
|
|
computation failed. This is a strictly more general form of <code>Option</code>. Consider
|
|
the following type alias, which is semantically equivalent to the real
|
|
<code>Option<T></code> in every way:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
type Option<T> = Result<T, ()>;
|
|
|
|
#}</code></pre></pre>
|
|
<p>This fixes the second type parameter of <code>Result</code> to always be <code>()</code> (pronounced
|
|
“unit” or “empty tuple”). Exactly one value inhabits the <code>()</code> type: <code>()</code>. (Yup,
|
|
the type and value level terms have the same notation!)</p>
|
|
<p>The <code>Result</code> type is a way of representing one of two possible outcomes in a
|
|
computation. By convention, one outcome is meant to be expected or “<code>Ok</code>” while
|
|
the other outcome is meant to be unexpected or “<code>Err</code>”.</p>
|
|
<p>Just like <code>Option</code>, the <code>Result</code> type also has an
|
|
<a href="../../std/result/enum.Result.html#method.unwrap"><code>unwrap</code> method
|
|
defined</a>
|
|
in the standard library. Let's define it:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# enum Result<T, E> { Ok(T), Err(E) }
|
|
impl<T, E: ::std::fmt::Debug> Result<T, E> {
|
|
fn unwrap(self) -> T {
|
|
match self {
|
|
Result::Ok(val) => val,
|
|
Result::Err(err) =>
|
|
panic!("called `Result::unwrap()` on an `Err` value: {:?}", err),
|
|
}
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>This is effectively the same as our <a href="error-handling.html#code-option-def-unwrap">definition for
|
|
<code>Option::unwrap</code></a>, except it includes the
|
|
error value in the <code>panic!</code> message. This makes debugging easier, but
|
|
it also requires us to add a <a href="../../std/fmt/trait.Debug.html"><code>Debug</code></a> constraint on the <code>E</code> type
|
|
parameter (which represents our error type). Since the vast majority
|
|
of types should satisfy the <code>Debug</code> constraint, this tends to work out
|
|
in practice. (<code>Debug</code> on a type simply means that there's a reasonable
|
|
way to print a human readable description of values with that type.)</p>
|
|
<p>OK, let's move on to an example.</p>
|
|
<a class="header" href="error-handling.html#parsing-integers" id="parsing-integers"><h3>Parsing integers</h3></a>
|
|
<p>The Rust standard library makes converting strings to integers dead simple.
|
|
It's so easy in fact, that it is very tempting to write something like the
|
|
following:</p>
|
|
<pre><pre class="playpen"><code class="language-rust">fn double_number(number_str: &str) -> i32 {
|
|
2 * number_str.parse::<i32>().unwrap()
|
|
}
|
|
|
|
fn main() {
|
|
let n: i32 = double_number("10");
|
|
assert_eq!(n, 20);
|
|
}
|
|
</code></pre></pre>
|
|
<p>At this point, you should be skeptical of calling <code>unwrap</code>. For example, if
|
|
the string doesn't parse as a number, you'll get a panic:</p>
|
|
<pre><code class="language-text">thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', /home/rustbuild/src/rust-buildbot/slave/beta-dist-rustc-linux/build/src/libcore/result.rs:729
|
|
</code></pre>
|
|
<p>This is rather unsightly, and if this happened inside a library you're
|
|
using, you might be understandably annoyed. Instead, we should try to
|
|
handle the error in our function and let the caller decide what to
|
|
do. This means changing the return type of <code>double_number</code>. But to
|
|
what? Well, that requires looking at the signature of the <a href="../../std/primitive.str.html#method.parse"><code>parse</code>
|
|
method</a> in the standard library:</p>
|
|
<pre><code class="language-rust ignore">impl str {
|
|
fn parse<F: FromStr>(&self) -> Result<F, F::Err>;
|
|
}
|
|
</code></pre>
|
|
<p>Hmm. So we at least know that we need to use a <code>Result</code>. Certainly, it's
|
|
possible that this could have returned an <code>Option</code>. After all, a string either
|
|
parses as a number or it doesn't, right? That's certainly a reasonable way to
|
|
go, but the implementation internally distinguishes <em>why</em> the string didn't
|
|
parse as an integer. (Whether it's an empty string, an invalid digit, too big
|
|
or too small.) Therefore, using a <code>Result</code> makes sense because we want to
|
|
provide more information than simply “absence.” We want to say <em>why</em> the
|
|
parsing failed. You should try to emulate this line of reasoning when faced
|
|
with a choice between <code>Option</code> and <code>Result</code>. If you can provide detailed error
|
|
information, then you probably should. (We'll see more on this later.)</p>
|
|
<p>OK, but how do we write our return type? The <code>parse</code> method as defined
|
|
above is generic over all the different number types defined in the
|
|
standard library. We could (and probably should) also make our
|
|
function generic, but let's favor explicitness for the moment. We only
|
|
care about <code>i32</code>, so we need to <a href="../../std/primitive.i32.html">find its implementation of
|
|
<code>FromStr</code></a> (do a <code>CTRL-F</code> in your browser
|
|
for “FromStr”) and look at its <a href="associated-types.html">associated type</a> <code>Err</code>. We did
|
|
this so we can find the concrete error type. In this case, it's
|
|
<a href="../../std/num/struct.ParseIntError.html"><code>std::num::ParseIntError</code></a>.
|
|
Finally, we can rewrite our function:</p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::num::ParseIntError;
|
|
|
|
fn double_number(number_str: &str) -> Result<i32, ParseIntError> {
|
|
match number_str.parse::<i32>() {
|
|
Ok(n) => Ok(2 * n),
|
|
Err(err) => Err(err),
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
match double_number("10") {
|
|
Ok(n) => assert_eq!(n, 20),
|
|
Err(err) => println!("Error: {:?}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>This is a little better, but now we've written a lot more code! The case
|
|
analysis has once again bitten us.</p>
|
|
<p>Combinators to the rescue! Just like <code>Option</code>, <code>Result</code> has lots of combinators
|
|
defined as methods. There is a large intersection of common combinators between
|
|
<code>Result</code> and <code>Option</code>. In particular, <code>map</code> is part of that intersection:</p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::num::ParseIntError;
|
|
|
|
fn double_number(number_str: &str) -> Result<i32, ParseIntError> {
|
|
number_str.parse::<i32>().map(|n| 2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match double_number("10") {
|
|
Ok(n) => assert_eq!(n, 20),
|
|
Err(err) => println!("Error: {:?}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>The usual suspects are all there for <code>Result</code>, including
|
|
<a href="../../std/result/enum.Result.html#method.unwrap_or"><code>unwrap_or</code></a> and
|
|
<a href="../../std/result/enum.Result.html#method.and_then"><code>and_then</code></a>.
|
|
Additionally, since <code>Result</code> has a second type parameter, there are
|
|
combinators that affect only the error type, such as
|
|
<a href="../../std/result/enum.Result.html#method.map_err"><code>map_err</code></a> (instead of
|
|
<code>map</code>) and <a href="../../std/result/enum.Result.html#method.or_else"><code>or_else</code></a>
|
|
(instead of <code>and_then</code>).</p>
|
|
<a class="header" href="error-handling.html#the-result-type-alias-idiom" id="the-result-type-alias-idiom"><h3>The <code>Result</code> type alias idiom</h3></a>
|
|
<p>In the standard library, you may frequently see types like
|
|
<code>Result<i32></code>. But wait, <a href="error-handling.html#code-result-def">we defined <code>Result</code></a> to
|
|
have two type parameters. How can we get away with only specifying
|
|
one? The key is to define a <code>Result</code> type alias that <em>fixes</em> one of
|
|
the type parameters to a particular type. Usually the fixed type is
|
|
the error type. For example, our previous example parsing integers
|
|
could be rewritten like this:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::num::ParseIntError;
|
|
use std::result;
|
|
|
|
type Result<T> = result::Result<T, ParseIntError>;
|
|
|
|
fn double_number(number_str: &str) -> Result<i32> {
|
|
unimplemented!();
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Why would we do this? Well, if we have a lot of functions that could return
|
|
<code>ParseIntError</code>, then it's much more convenient to define an alias that always
|
|
uses <code>ParseIntError</code> so that we don't have to write it out all the time.</p>
|
|
<p>The most prominent place this idiom is used in the standard library is
|
|
with <a href="../../std/io/type.Result.html"><code>io::Result</code></a>. Typically, one writes
|
|
<code>io::Result<T></code>, which makes it clear that you're using the <code>io</code>
|
|
module's type alias instead of the plain definition from
|
|
<code>std::result</code>. (This idiom is also used for
|
|
<a href="../../std/fmt/type.Result.html"><code>fmt::Result</code></a>.)</p>
|
|
<a class="header" href="error-handling.html#a-brief-interlude-unwrapping-isnt-evil" id="a-brief-interlude-unwrapping-isnt-evil"><h2>A brief interlude: unwrapping isn't evil</h2></a>
|
|
<p>If you've been following along, you might have noticed that I've taken a pretty
|
|
hard line against calling methods like <code>unwrap</code> that could <code>panic</code> and abort
|
|
your program. <em>Generally speaking</em>, this is good advice.</p>
|
|
<p>However, <code>unwrap</code> can still be used judiciously. What exactly justifies use of
|
|
<code>unwrap</code> is somewhat of a grey area and reasonable people can disagree. I'll
|
|
summarize some of my <em>opinions</em> on the matter.</p>
|
|
<ul>
|
|
<li><strong>In examples and quick 'n' dirty code.</strong> Sometimes you're writing examples
|
|
or a quick program, and error handling simply isn't important. Beating the
|
|
convenience of <code>unwrap</code> can be hard in such scenarios, so it is very
|
|
appealing.</li>
|
|
<li><strong>When panicking indicates a bug in the program.</strong> When the invariants of
|
|
your code should prevent a certain case from happening (like, say, popping
|
|
from an empty stack), then panicking can be permissible. This is because it
|
|
exposes a bug in your program. This can be explicit, like from an <code>assert!</code>
|
|
failing, or it could be because your index into an array was out of bounds.</li>
|
|
</ul>
|
|
<p>This is probably not an exhaustive list. Moreover, when using an
|
|
<code>Option</code>, it is often better to use its
|
|
<a href="../../std/option/enum.Option.html#method.expect"><code>expect</code></a>
|
|
method. <code>expect</code> does exactly the same thing as <code>unwrap</code>, except it
|
|
prints a message you give to <code>expect</code>. This makes the resulting panic
|
|
a bit nicer to deal with, since it will show your message instead of
|
|
“called unwrap on a <code>None</code> value.”</p>
|
|
<p>My advice boils down to this: use good judgment. There's a reason why the words
|
|
“never do X” or “Y is considered harmful” don't appear in my writing. There are
|
|
trade offs to all things, and it is up to you as the programmer to determine
|
|
what is acceptable for your use cases. My goal is only to help you evaluate
|
|
trade offs as accurately as possible.</p>
|
|
<p>Now that we've covered the basics of error handling in Rust, and
|
|
explained unwrapping, let's start exploring more of the standard
|
|
library.</p>
|
|
<a class="header" href="error-handling.html#working-with-multiple-error-types" id="working-with-multiple-error-types"><h1>Working with multiple error types</h1></a>
|
|
<p>Thus far, we've looked at error handling where everything was either an
|
|
<code>Option<T></code> or a <code>Result<T, SomeError></code>. But what happens when you have both an
|
|
<code>Option</code> and a <code>Result</code>? Or what if you have a <code>Result<T, Error1></code> and a
|
|
<code>Result<T, Error2></code>? Handling <em>composition of distinct error types</em> is the next
|
|
challenge in front of us, and it will be the major theme throughout the rest of
|
|
this section.</p>
|
|
<a class="header" href="error-handling.html#composing-option-and-result" id="composing-option-and-result"><h2>Composing <code>Option</code> and <code>Result</code></h2></a>
|
|
<p>So far, I've talked about combinators defined for <code>Option</code> and combinators
|
|
defined for <code>Result</code>. We can use these combinators to compose results of
|
|
different computations without doing explicit case analysis.</p>
|
|
<p>Of course, in real code, things aren't always as clean. Sometimes you have a
|
|
mix of <code>Option</code> and <code>Result</code> types. Must we resort to explicit case analysis,
|
|
or can we continue using combinators?</p>
|
|
<p>For now, let's revisit one of the first examples in this section:</p>
|
|
<pre><pre class="playpen"><code class="language-rust should_panic">use std::env;
|
|
|
|
fn main() {
|
|
let mut argv = env::args();
|
|
let arg: String = argv.nth(1).unwrap(); // error 1
|
|
let n: i32 = arg.parse().unwrap(); // error 2
|
|
println!("{}", 2 * n);
|
|
}
|
|
</code></pre></pre>
|
|
<p>Given our new found knowledge of <code>Option</code>, <code>Result</code> and their various
|
|
combinators, we should try to rewrite this so that errors are handled properly
|
|
and the program doesn't panic if there's an error.</p>
|
|
<p>The tricky aspect here is that <code>argv.nth(1)</code> produces an <code>Option</code> while
|
|
<code>arg.parse()</code> produces a <code>Result</code>. These aren't directly composable. When faced
|
|
with both an <code>Option</code> and a <code>Result</code>, the solution is <em>usually</em> to convert the
|
|
<code>Option</code> to a <code>Result</code>. In our case, the absence of a command line parameter
|
|
(from <code>env::args()</code>) means the user didn't invoke the program correctly. We
|
|
could use a <code>String</code> to describe the error. Let's try:</p>
|
|
<p><span id="code-error-double-string"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::env;
|
|
|
|
fn double_arg(mut argv: env::Args) -> Result<i32, String> {
|
|
argv.nth(1)
|
|
.ok_or("Please give at least one argument".to_owned())
|
|
.and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string()))
|
|
.map(|n| 2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match double_arg(env::args()) {
|
|
Ok(n) => println!("{}", n),
|
|
Err(err) => println!("Error: {}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>There are a couple new things in this example. The first is the use of the
|
|
<a href="../../std/option/enum.Option.html#method.ok_or"><code>Option::ok_or</code></a>
|
|
combinator. This is one way to convert an <code>Option</code> into a <code>Result</code>. The
|
|
conversion requires you to specify what error to use if <code>Option</code> is <code>None</code>.
|
|
Like the other combinators we've seen, its definition is very simple:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
fn ok_or<T, E>(option: Option<T>, err: E) -> Result<T, E> {
|
|
match option {
|
|
Some(val) => Ok(val),
|
|
None => Err(err),
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>The other new combinator used here is
|
|
<a href="../../std/result/enum.Result.html#method.map_err"><code>Result::map_err</code></a>.
|
|
This is like <code>Result::map</code>, except it maps a function on to the <em>error</em>
|
|
portion of a <code>Result</code> value. If the <code>Result</code> is an <code>Ok(...)</code> value, then it is
|
|
returned unmodified.</p>
|
|
<p>We use <code>map_err</code> here because it is necessary for the error types to remain
|
|
the same (because of our use of <code>and_then</code>). Since we chose to convert the
|
|
<code>Option<String></code> (from <code>argv.nth(1)</code>) to a <code>Result<String, String></code>, we must
|
|
also convert the <code>ParseIntError</code> from <code>arg.parse()</code> to a <code>String</code>.</p>
|
|
<a class="header" href="error-handling.html#the-limits-of-combinators" id="the-limits-of-combinators"><h2>The limits of combinators</h2></a>
|
|
<p>Doing IO and parsing input is a very common task, and it's one that I
|
|
personally have done a lot of in Rust. Therefore, we will use (and continue to
|
|
use) IO and various parsing routines to exemplify error handling.</p>
|
|
<p>Let's start simple. We are tasked with opening a file, reading all of its
|
|
contents and converting its contents to a number. Then we multiply it by <code>2</code>
|
|
and print the output.</p>
|
|
<p>Although I've tried to convince you not to use <code>unwrap</code>, it can be useful
|
|
to first write your code using <code>unwrap</code>. It allows you to focus on your problem
|
|
instead of the error handling, and it exposes the points where proper error
|
|
handling need to occur. Let's start there so we can get a handle on the code,
|
|
and then refactor it to use better error handling.</p>
|
|
<pre><pre class="playpen"><code class="language-rust should_panic">use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> i32 {
|
|
let mut file = File::open(file_path).unwrap(); // error 1
|
|
let mut contents = String::new();
|
|
file.read_to_string(&mut contents).unwrap(); // error 2
|
|
let n: i32 = contents.trim().parse().unwrap(); // error 3
|
|
2 * n
|
|
}
|
|
|
|
fn main() {
|
|
let doubled = file_double("foobar");
|
|
println!("{}", doubled);
|
|
}
|
|
</code></pre></pre>
|
|
<p>(N.B. The <code>AsRef<Path></code> is used because those are the
|
|
<a href="../../std/fs/struct.File.html#method.open">same bounds used on
|
|
<code>std::fs::File::open</code></a>.
|
|
This makes it ergonomic to use any kind of string as a file path.)</p>
|
|
<p>There are three different errors that can occur here:</p>
|
|
<ol>
|
|
<li>A problem opening the file.</li>
|
|
<li>A problem reading data from the file.</li>
|
|
<li>A problem parsing the data as a number.</li>
|
|
</ol>
|
|
<p>The first two problems are described via the
|
|
<a href="../../std/io/struct.Error.html"><code>std::io::Error</code></a> type. We know this
|
|
because of the return types of
|
|
<a href="../../std/fs/struct.File.html#method.open"><code>std::fs::File::open</code></a> and
|
|
<a href="../../std/io/trait.Read.html#method.read_to_string"><code>std::io::Read::read_to_string</code></a>.
|
|
(Note that they both use the <a href="error-handling.html#the-result-type-alias-idiom"><code>Result</code> type alias
|
|
idiom</a> described previously. If you
|
|
click on the <code>Result</code> type, you'll <a href="../../std/io/type.Result.html">see the type
|
|
alias</a>, and consequently, the underlying
|
|
<code>io::Error</code> type.) The third problem is described by the
|
|
<a href="../../std/num/struct.ParseIntError.html"><code>std::num::ParseIntError</code></a>
|
|
type. The <code>io::Error</code> type in particular is <em>pervasive</em> throughout the
|
|
standard library. You will see it again and again.</p>
|
|
<p>Let's start the process of refactoring the <code>file_double</code> function. To make this
|
|
function composable with other components of the program, it should <em>not</em> panic
|
|
if any of the above error conditions are met. Effectively, this means that the
|
|
function should <em>return an error</em> if any of its operations fail. Our problem is
|
|
that the return type of <code>file_double</code> is <code>i32</code>, which does not give us any
|
|
useful way of reporting an error. Thus, we must start by changing the return
|
|
type from <code>i32</code> to something else.</p>
|
|
<p>The first thing we need to decide: should we use <code>Option</code> or <code>Result</code>? We
|
|
certainly could use <code>Option</code> very easily. If any of the three errors occur, we
|
|
could simply return <code>None</code>. This will work <em>and it is better than panicking</em>,
|
|
but we can do a lot better. Instead, we should pass some detail about the error
|
|
that occurred. Since we want to express the <em>possibility of error</em>, we should
|
|
use <code>Result<i32, E></code>. But what should <code>E</code> be? Since two <em>different</em> types of
|
|
errors can occur, we need to convert them to a common type. One such type is
|
|
<code>String</code>. Let's see how that impacts our code:</p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {
|
|
File::open(file_path)
|
|
.map_err(|err| err.to_string())
|
|
.and_then(|mut file| {
|
|
let mut contents = String::new();
|
|
file.read_to_string(&mut contents)
|
|
.map_err(|err| err.to_string())
|
|
.map(|_| contents)
|
|
})
|
|
.and_then(|contents| {
|
|
contents.trim().parse::<i32>()
|
|
.map_err(|err| err.to_string())
|
|
})
|
|
.map(|n| 2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match file_double("foobar") {
|
|
Ok(n) => println!("{}", n),
|
|
Err(err) => println!("Error: {}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>This code looks a bit hairy. It can take quite a bit of practice before code
|
|
like this becomes easy to write. The way we write it is by <em>following the
|
|
types</em>. As soon as we changed the return type of <code>file_double</code> to
|
|
<code>Result<i32, String></code>, we had to start looking for the right combinators. In
|
|
this case, we only used three different combinators: <code>and_then</code>, <code>map</code> and
|
|
<code>map_err</code>.</p>
|
|
<p><code>and_then</code> is used to chain multiple computations where each computation could
|
|
return an error. After opening the file, there are two more computations that
|
|
could fail: reading from the file and parsing the contents as a number.
|
|
Correspondingly, there are two calls to <code>and_then</code>.</p>
|
|
<p><code>map</code> is used to apply a function to the <code>Ok(...)</code> value of a <code>Result</code>. For
|
|
example, the very last call to <code>map</code> multiplies the <code>Ok(...)</code> value (which is
|
|
an <code>i32</code>) by <code>2</code>. If an error had occurred before that point, this operation
|
|
would have been skipped because of how <code>map</code> is defined.</p>
|
|
<p><code>map_err</code> is the trick that makes all of this work. <code>map_err</code> is like
|
|
<code>map</code>, except it applies a function to the <code>Err(...)</code> value of a <code>Result</code>. In
|
|
this case, we want to convert all of our errors to one type: <code>String</code>. Since
|
|
both <code>io::Error</code> and <code>num::ParseIntError</code> implement <code>ToString</code>, we can call the
|
|
<code>to_string()</code> method to convert them.</p>
|
|
<p>With all of that said, the code is still hairy. Mastering use of combinators is
|
|
important, but they have their limits. Let's try a different approach: early
|
|
returns.</p>
|
|
<a class="header" href="error-handling.html#early-returns" id="early-returns"><h2>Early returns</h2></a>
|
|
<p>I'd like to take the code from the previous section and rewrite it using <em>early
|
|
returns</em>. Early returns let you exit the function early. We can't return early
|
|
in <code>file_double</code> from inside another closure, so we'll need to revert back to
|
|
explicit case analysis.</p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {
|
|
let mut file = match File::open(file_path) {
|
|
Ok(file) => file,
|
|
Err(err) => return Err(err.to_string()),
|
|
};
|
|
let mut contents = String::new();
|
|
if let Err(err) = file.read_to_string(&mut contents) {
|
|
return Err(err.to_string());
|
|
}
|
|
let n: i32 = match contents.trim().parse() {
|
|
Ok(n) => n,
|
|
Err(err) => return Err(err.to_string()),
|
|
};
|
|
Ok(2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match file_double("foobar") {
|
|
Ok(n) => println!("{}", n),
|
|
Err(err) => println!("Error: {}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>Reasonable people can disagree over whether this code is better than the code
|
|
that uses combinators, but if you aren't familiar with the combinator approach,
|
|
this code looks simpler to read to me. It uses explicit case analysis with
|
|
<code>match</code> and <code>if let</code>. If an error occurs, it simply stops executing the
|
|
function and returns the error (by converting it to a string).</p>
|
|
<p>Isn't this a step backwards though? Previously, we said that the key to
|
|
ergonomic error handling is reducing explicit case analysis, yet we've reverted
|
|
back to explicit case analysis here. It turns out, there are <em>multiple</em> ways to
|
|
reduce explicit case analysis. Combinators aren't the only way.</p>
|
|
<a class="header" href="error-handling.html#the-try-macro" id="the-try-macro"><h2>The <code>try!</code> macro</h2></a>
|
|
<p>A cornerstone of error handling in Rust is the <code>try!</code> macro. The <code>try!</code> macro
|
|
abstracts case analysis like combinators, but unlike combinators, it also
|
|
abstracts <em>control flow</em>. Namely, it can abstract the <em>early return</em> pattern
|
|
seen above.</p>
|
|
<p>Here is a simplified definition of a <code>try!</code> macro:</p>
|
|
<p><span id="code-try-def-simple"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
macro_rules! try {
|
|
($e:expr) => (match $e {
|
|
Ok(val) => val,
|
|
Err(err) => return Err(err),
|
|
});
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>(The <a href="../../std/macro.try.html">real definition</a> is a bit more
|
|
sophisticated. We will address that later.)</p>
|
|
<p>Using the <code>try!</code> macro makes it very easy to simplify our last example. Since
|
|
it does the case analysis and the early return for us, we get tighter code that
|
|
is easier to read:</p>
|
|
<pre><pre class="playpen"><code class="language-rust">use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {
|
|
let mut file = try!(File::open(file_path).map_err(|e| e.to_string()));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents).map_err(|e| e.to_string()));
|
|
let n = try!(contents.trim().parse::<i32>().map_err(|e| e.to_string()));
|
|
Ok(2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match file_double("foobar") {
|
|
Ok(n) => println!("{}", n),
|
|
Err(err) => println!("Error: {}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>The <code>map_err</code> calls are still necessary given
|
|
<a href="error-handling.html#code-try-def-simple">our definition of <code>try!</code></a>.
|
|
This is because the error types still need to be converted to <code>String</code>.
|
|
The good news is that we will soon learn how to remove those <code>map_err</code> calls!
|
|
The bad news is that we will need to learn a bit more about a couple important
|
|
traits in the standard library before we can remove the <code>map_err</code> calls.</p>
|
|
<a class="header" href="error-handling.html#defining-your-own-error-type" id="defining-your-own-error-type"><h2>Defining your own error type</h2></a>
|
|
<p>Before we dive into some of the standard library error traits, I'd like to wrap
|
|
up this section by removing the use of <code>String</code> as our error type in the
|
|
previous examples.</p>
|
|
<p>Using <code>String</code> as we did in our previous examples is convenient because it's
|
|
easy to convert errors to strings, or even make up your own errors as strings
|
|
on the spot. However, using <code>String</code> for your errors has some downsides.</p>
|
|
<p>The first downside is that the error messages tend to clutter your
|
|
code. It's possible to define the error messages elsewhere, but unless
|
|
you're unusually disciplined, it is very tempting to embed the error
|
|
message into your code. Indeed, we did exactly this in a <a href="error-handling.html#code-error-double-string">previous
|
|
example</a>.</p>
|
|
<p>The second and more important downside is that <code>String</code>s are <em>lossy</em>. That is,
|
|
if all errors are converted to strings, then the errors we pass to the caller
|
|
become completely opaque. The only reasonable thing the caller can do with a
|
|
<code>String</code> error is show it to the user. Certainly, inspecting the string to
|
|
determine the type of error is not robust. (Admittedly, this downside is far
|
|
more important inside of a library as opposed to, say, an application.)</p>
|
|
<p>For example, the <code>io::Error</code> type embeds an
|
|
<a href="../../std/io/enum.ErrorKind.html"><code>io::ErrorKind</code></a>,
|
|
which is <em>structured data</em> that represents what went wrong during an IO
|
|
operation. This is important because you might want to react differently
|
|
depending on the error. (e.g., A <code>BrokenPipe</code> error might mean quitting your
|
|
program gracefully while a <code>NotFound</code> error might mean exiting with an error
|
|
code and showing an error to the user.) With <code>io::ErrorKind</code>, the caller can
|
|
examine the type of an error with case analysis, which is strictly superior
|
|
to trying to tease out the details of an error inside of a <code>String</code>.</p>
|
|
<p>Instead of using a <code>String</code> as an error type in our previous example of reading
|
|
an integer from a file, we can define our own error type that represents errors
|
|
with <em>structured data</em>. We endeavor to not drop information from underlying
|
|
errors in case the caller wants to inspect the details.</p>
|
|
<p>The ideal way to represent <em>one of many possibilities</em> is to define our own
|
|
sum type using <code>enum</code>. In our case, an error is either an <code>io::Error</code> or a
|
|
<code>num::ParseIntError</code>, so a natural definition arises:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::io;
|
|
use std::num;
|
|
|
|
// We derive `Debug` because all types should probably derive `Debug`.
|
|
// This gives us a reasonable human readable description of `CliError` values.
|
|
#[derive(Debug)]
|
|
enum CliError {
|
|
Io(io::Error),
|
|
Parse(num::ParseIntError),
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Tweaking our code is very easy. Instead of converting errors to strings, we
|
|
simply convert them to our <code>CliError</code> type using the corresponding value
|
|
constructor:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #[derive(Debug)]
|
|
# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) }
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {
|
|
let mut file = try!(File::open(file_path).map_err(CliError::Io));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents).map_err(CliError::Io));
|
|
let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse));
|
|
Ok(2 * n)
|
|
}
|
|
|
|
fn main() {
|
|
match file_double("foobar") {
|
|
Ok(n) => println!("{}", n),
|
|
Err(err) => println!("Error: {:?}", err),
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<p>The only change here is switching <code>map_err(|e| e.to_string())</code> (which converts
|
|
errors to strings) to <code>map_err(CliError::Io)</code> or <code>map_err(CliError::Parse)</code>.
|
|
The <em>caller</em> gets to decide the level of detail to report to the user. In
|
|
effect, using a <code>String</code> as an error type removes choices from the caller while
|
|
using a custom <code>enum</code> error type like <code>CliError</code> gives the caller all of the
|
|
conveniences as before in addition to <em>structured data</em> describing the error.</p>
|
|
<p>A rule of thumb is to define your own error type, but a <code>String</code> error type
|
|
will do in a pinch, particularly if you're writing an application. If you're
|
|
writing a library, defining your own error type should be strongly preferred so
|
|
that you don't remove choices from the caller unnecessarily.</p>
|
|
<a class="header" href="error-handling.html#standard-library-traits-used-for-error-handling" id="standard-library-traits-used-for-error-handling"><h1>Standard library traits used for error handling</h1></a>
|
|
<p>The standard library defines two integral traits for error handling:
|
|
<a href="../../std/error/trait.Error.html"><code>std::error::Error</code></a> and
|
|
<a href="../../std/convert/trait.From.html"><code>std::convert::From</code></a>. While <code>Error</code>
|
|
is designed specifically for generically describing errors, the <code>From</code>
|
|
trait serves a more general role for converting values between two
|
|
distinct types.</p>
|
|
<a class="header" href="error-handling.html#the-error-trait" id="the-error-trait"><h2>The <code>Error</code> trait</h2></a>
|
|
<p>The <code>Error</code> trait is <a href="../../std/error/trait.Error.html">defined in the standard
|
|
library</a>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::fmt::{Debug, Display};
|
|
|
|
trait Error: Debug + Display {
|
|
/// A short description of the error.
|
|
fn description(&self) -> &str;
|
|
|
|
/// The lower level cause of this error, if any.
|
|
fn cause(&self) -> Option<&Error> { None }
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>This trait is super generic because it is meant to be implemented for <em>all</em>
|
|
types that represent errors. This will prove useful for writing composable code
|
|
as we'll see later. Otherwise, the trait allows you to do at least the
|
|
following things:</p>
|
|
<ul>
|
|
<li>Obtain a <code>Debug</code> representation of the error.</li>
|
|
<li>Obtain a user-facing <code>Display</code> representation of the error.</li>
|
|
<li>Obtain a short description of the error (via the <code>description</code> method).</li>
|
|
<li>Inspect the causal chain of an error, if one exists (via the <code>cause</code> method).</li>
|
|
</ul>
|
|
<p>The first two are a result of <code>Error</code> requiring impls for both <code>Debug</code> and
|
|
<code>Display</code>. The latter two are from the two methods defined on <code>Error</code>. The
|
|
power of <code>Error</code> comes from the fact that all error types impl <code>Error</code>, which
|
|
means errors can be existentially quantified as a
|
|
<a href="trait-objects.html">trait object</a>.
|
|
This manifests as either <code>Box<Error></code> or <code>&Error</code>. Indeed, the <code>cause</code> method
|
|
returns an <code>&Error</code>, which is itself a trait object. We'll revisit the
|
|
<code>Error</code> trait's utility as a trait object later.</p>
|
|
<p>For now, it suffices to show an example implementing the <code>Error</code> trait. Let's
|
|
use the error type we defined in the
|
|
<a href="error-handling.html#defining-your-own-error-type">previous section</a>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::io;
|
|
use std::num;
|
|
|
|
// We derive `Debug` because all types should probably derive `Debug`.
|
|
// This gives us a reasonable human readable description of `CliError` values.
|
|
#[derive(Debug)]
|
|
enum CliError {
|
|
Io(io::Error),
|
|
Parse(num::ParseIntError),
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>This particular error type represents the possibility of two types of errors
|
|
occurring: an error dealing with I/O or an error converting a string to a
|
|
number. The error could represent as many error types as you want by adding new
|
|
variants to the <code>enum</code> definition.</p>
|
|
<p>Implementing <code>Error</code> is pretty straight-forward. It's mostly going to be a lot
|
|
explicit case analysis.</p>
|
|
<pre><code class="language-rust ignore">use std::error;
|
|
use std::fmt;
|
|
|
|
impl fmt::Display for CliError {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match *self {
|
|
// Both underlying errors already impl `Display`, so we defer to
|
|
// their implementations.
|
|
CliError::Io(ref err) => write!(f, "IO error: {}", err),
|
|
CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl error::Error for CliError {
|
|
fn description(&self) -> &str {
|
|
// Both underlying errors already impl `Error`, so we defer to their
|
|
// implementations.
|
|
match *self {
|
|
CliError::Io(ref err) => err.description(),
|
|
CliError::Parse(ref err) => err.description(),
|
|
}
|
|
}
|
|
|
|
fn cause(&self) -> Option<&error::Error> {
|
|
match *self {
|
|
// N.B. Both of these implicitly cast `err` from their concrete
|
|
// types (either `&io::Error` or `&num::ParseIntError`)
|
|
// to a trait object `&Error`. This works because both error types
|
|
// implement `Error`.
|
|
CliError::Io(ref err) => Some(err),
|
|
CliError::Parse(ref err) => Some(err),
|
|
}
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>We note that this is a very typical implementation of <code>Error</code>: match on your
|
|
different error types and satisfy the contracts defined for <code>description</code> and
|
|
<code>cause</code>.</p>
|
|
<a class="header" href="error-handling.html#the-from-trait" id="the-from-trait"><h2>The <code>From</code> trait</h2></a>
|
|
<p>The <code>std::convert::From</code> trait is
|
|
<a href="../../std/convert/trait.From.html">defined in the standard
|
|
library</a>:</p>
|
|
<p><span id="code-from-def"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
trait From<T> {
|
|
fn from(T) -> Self;
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Deliciously simple, yes? <code>From</code> is very useful because it gives us a generic
|
|
way to talk about conversion <em>from</em> a particular type <code>T</code> to some other type
|
|
(in this case, “some other type” is the subject of the impl, or <code>Self</code>).
|
|
The crux of <code>From</code> is the
|
|
<a href="../../std/convert/trait.From.html">set of implementations provided by the standard
|
|
library</a>.</p>
|
|
<p>Here are a few simple examples demonstrating how <code>From</code> works:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
let string: String = From::from("foo");
|
|
let bytes: Vec<u8> = From::from("foo");
|
|
let cow: ::std::borrow::Cow<str> = From::from("foo");
|
|
|
|
#}</code></pre></pre>
|
|
<p>OK, so <code>From</code> is useful for converting between strings. But what about errors?
|
|
It turns out, there is one critical impl:</p>
|
|
<pre><code class="language-rust ignore">impl<'a, E: Error + 'a> From<E> for Box<Error + 'a>
|
|
</code></pre>
|
|
<p>This impl says that for <em>any</em> type that impls <code>Error</code>, we can convert it to a
|
|
trait object <code>Box<Error></code>. This may not seem terribly surprising, but it is
|
|
useful in a generic context.</p>
|
|
<p>Remember the two errors we were dealing with previously? Specifically,
|
|
<code>io::Error</code> and <code>num::ParseIntError</code>. Since both impl <code>Error</code>, they work with
|
|
<code>From</code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::error::Error;
|
|
use std::fs;
|
|
use std::io;
|
|
use std::num;
|
|
|
|
// We have to jump through some hoops to actually get error values:
|
|
let io_err: io::Error = io::Error::last_os_error();
|
|
let parse_err: num::ParseIntError = "not a number".parse::<i32>().unwrap_err();
|
|
|
|
// OK, here are the conversions:
|
|
let err1: Box<Error> = From::from(io_err);
|
|
let err2: Box<Error> = From::from(parse_err);
|
|
|
|
#}</code></pre></pre>
|
|
<p>There is a really important pattern to recognize here. Both <code>err1</code> and <code>err2</code>
|
|
have the <em>same type</em>. This is because they are existentially quantified types,
|
|
or trait objects. In particular, their underlying type is <em>erased</em> from the
|
|
compiler's knowledge, so it truly sees <code>err1</code> and <code>err2</code> as exactly the same.
|
|
Additionally, we constructed <code>err1</code> and <code>err2</code> using precisely the same
|
|
function call: <code>From::from</code>. This is because <code>From::from</code> is overloaded on both
|
|
its argument and its return type.</p>
|
|
<p>This pattern is important because it solves a problem we had earlier: it gives
|
|
us a way to reliably convert errors to the same type using the same function.</p>
|
|
<p>Time to revisit an old friend; the <code>try!</code> macro.</p>
|
|
<a class="header" href="error-handling.html#the-real-try-macro" id="the-real-try-macro"><h2>The real <code>try!</code> macro</h2></a>
|
|
<p>Previously, we presented this definition of <code>try!</code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
macro_rules! try {
|
|
($e:expr) => (match $e {
|
|
Ok(val) => val,
|
|
Err(err) => return Err(err),
|
|
});
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>This is not its real definition. Its real definition is
|
|
<a href="../../std/macro.try.html">in the standard library</a>:</p>
|
|
<p><span id="code-try-def"></span></p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
macro_rules! try {
|
|
($e:expr) => (match $e {
|
|
Ok(val) => val,
|
|
Err(err) => return Err(::std::convert::From::from(err)),
|
|
});
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>There's one tiny but powerful change: the error value is passed through
|
|
<code>From::from</code>. This makes the <code>try!</code> macro a lot more powerful because it gives
|
|
you automatic type conversion for free.</p>
|
|
<p>Armed with our more powerful <code>try!</code> macro, let's take a look at code we wrote
|
|
previously to read a file and convert its contents to an integer:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {
|
|
let mut file = try!(File::open(file_path).map_err(|e| e.to_string()));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents).map_err(|e| e.to_string()));
|
|
let n = try!(contents.trim().parse::<i32>().map_err(|e| e.to_string()));
|
|
Ok(2 * n)
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Earlier, we promised that we could get rid of the <code>map_err</code> calls. Indeed, all
|
|
we have to do is pick a type that <code>From</code> works with. As we saw in the previous
|
|
section, <code>From</code> has an impl that lets it convert any error type into a
|
|
<code>Box<Error></code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::error::Error;
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, Box<Error>> {
|
|
let mut file = try!(File::open(file_path));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents));
|
|
let n = try!(contents.trim().parse::<i32>());
|
|
Ok(2 * n)
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>We are getting very close to ideal error handling. Our code has very little
|
|
overhead as a result from error handling because the <code>try!</code> macro encapsulates
|
|
three things simultaneously:</p>
|
|
<ol>
|
|
<li>Case analysis.</li>
|
|
<li>Control flow.</li>
|
|
<li>Error type conversion.</li>
|
|
</ol>
|
|
<p>When all three things are combined, we get code that is unencumbered by
|
|
combinators, calls to <code>unwrap</code> or case analysis.</p>
|
|
<p>There's one little nit left: the <code>Box<Error></code> type is <em>opaque</em>. If we
|
|
return a <code>Box<Error></code> to the caller, the caller can't (easily) inspect
|
|
underlying error type. The situation is certainly better than <code>String</code>
|
|
because the caller can call methods like
|
|
<a href="../../std/error/trait.Error.html#tymethod.description"><code>description</code></a>
|
|
and <a href="../../std/error/trait.Error.html#method.cause"><code>cause</code></a>, but the
|
|
limitation remains: <code>Box<Error></code> is opaque. (N.B. This isn't entirely
|
|
true because Rust does have runtime reflection, which is useful in
|
|
some scenarios that are <a href="https://crates.io/crates/error">beyond the scope of this
|
|
section</a>.)</p>
|
|
<p>It's time to revisit our custom <code>CliError</code> type and tie everything together.</p>
|
|
<a class="header" href="error-handling.html#composing-custom-error-types" id="composing-custom-error-types"><h2>Composing custom error types</h2></a>
|
|
<p>In the last section, we looked at the real <code>try!</code> macro and how it does
|
|
automatic type conversion for us by calling <code>From::from</code> on the error value.
|
|
In particular, we converted errors to <code>Box<Error></code>, which works, but the type
|
|
is opaque to callers.</p>
|
|
<p>To fix this, we use the same remedy that we're already familiar with: a custom
|
|
error type. Once again, here is the code that reads the contents of a file and
|
|
converts it to an integer:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::fs::File;
|
|
use std::io::{self, Read};
|
|
use std::num;
|
|
use std::path::Path;
|
|
|
|
// We derive `Debug` because all types should probably derive `Debug`.
|
|
// This gives us a reasonable human readable description of `CliError` values.
|
|
#[derive(Debug)]
|
|
enum CliError {
|
|
Io(io::Error),
|
|
Parse(num::ParseIntError),
|
|
}
|
|
|
|
fn file_double_verbose<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {
|
|
let mut file = try!(File::open(file_path).map_err(CliError::Io));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents).map_err(CliError::Io));
|
|
let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse));
|
|
Ok(2 * n)
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>Notice that we still have the calls to <code>map_err</code>. Why? Well, recall the
|
|
definitions of <a href="error-handling.html#code-try-def"><code>try!</code></a> and <a href="error-handling.html#code-from-def"><code>From</code></a>. The
|
|
problem is that there is no <code>From</code> impl that allows us to convert from error
|
|
types like <code>io::Error</code> and <code>num::ParseIntError</code> to our own custom <code>CliError</code>.
|
|
Of course, it is easy to fix this! Since we defined <code>CliError</code>, we can impl
|
|
<code>From</code> with it:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# #[derive(Debug)]
|
|
# enum CliError { Io(io::Error), Parse(num::ParseIntError) }
|
|
use std::io;
|
|
use std::num;
|
|
|
|
impl From<io::Error> for CliError {
|
|
fn from(err: io::Error) -> CliError {
|
|
CliError::Io(err)
|
|
}
|
|
}
|
|
|
|
impl From<num::ParseIntError> for CliError {
|
|
fn from(err: num::ParseIntError) -> CliError {
|
|
CliError::Parse(err)
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>All these impls are doing is teaching <code>From</code> how to create a <code>CliError</code> from
|
|
other error types. In our case, construction is as simple as invoking the
|
|
corresponding value constructor. Indeed, it is <em>typically</em> this easy.</p>
|
|
<p>We can finally rewrite <code>file_double</code>:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# use std::io;
|
|
# use std::num;
|
|
# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) }
|
|
# impl From<io::Error> for CliError {
|
|
# fn from(err: io::Error) -> CliError { CliError::Io(err) }
|
|
# }
|
|
# impl From<num::ParseIntError> for CliError {
|
|
# fn from(err: num::ParseIntError) -> CliError { CliError::Parse(err) }
|
|
# }
|
|
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
use std::path::Path;
|
|
|
|
fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, CliError> {
|
|
let mut file = try!(File::open(file_path));
|
|
let mut contents = String::new();
|
|
try!(file.read_to_string(&mut contents));
|
|
let n: i32 = try!(contents.trim().parse());
|
|
Ok(2 * n)
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>The only thing we did here was remove the calls to <code>map_err</code>. They are no
|
|
longer needed because the <code>try!</code> macro invokes <code>From::from</code> on the error value.
|
|
This works because we've provided <code>From</code> impls for all the error types that
|
|
could appear.</p>
|
|
<p>If we modified our <code>file_double</code> function to perform some other operation, say,
|
|
convert a string to a float, then we'd need to add a new variant to our error
|
|
type:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
use std::io;
|
|
use std::num;
|
|
|
|
enum CliError {
|
|
Io(io::Error),
|
|
ParseInt(num::ParseIntError),
|
|
ParseFloat(num::ParseFloatError),
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>And add a new <code>From</code> impl:</p>
|
|
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
|
#
|
|
#fn main() {
|
|
# enum CliError {
|
|
# Io(::std::io::Error),
|
|
# ParseInt(num::ParseIntError),
|
|
# ParseFloat(num::ParseFloatError),
|
|
# }
|
|
|
|
use std::num;
|
|
|
|
impl From<num::ParseFloatError> for CliError {
|
|
fn from(err: num::ParseFloatError) -> CliError {
|
|
CliError::ParseFloat(err)
|
|
}
|
|
}
|
|
|
|
#}</code></pre></pre>
|
|
<p>And that's it!</p>
|
|
<a class="header" href="error-handling.html#advice-for-library-writers" id="advice-for-library-writers"><h2>Advice for library writers</h2></a>
|
|
<p>If your library needs to report custom errors, then you should
|
|
probably define your own error type. It's up to you whether or not to
|
|
expose its representation (like
|
|
<a href="../../std/io/enum.ErrorKind.html"><code>ErrorKind</code></a>) or keep it hidden (like
|
|
<a href="../../std/num/struct.ParseIntError.html"><code>ParseIntError</code></a>). Regardless
|
|
of how you do it, it's usually good practice to at least provide some
|
|
information about the error beyond its <code>String</code>
|
|
representation. But certainly, this will vary depending on use cases.</p>
|
|
<p>At a minimum, you should probably implement the
|
|
<a href="../../std/error/trait.Error.html"><code>Error</code></a>
|
|
trait. This will give users of your library some minimum flexibility for
|
|
<a href="error-handling.html#the-real-try-macro">composing errors</a>. Implementing the <code>Error</code> trait also
|
|
means that users are guaranteed the ability to obtain a string representation
|
|
of an error (because it requires impls for both <code>fmt::Debug</code> and
|
|
<code>fmt::Display</code>).</p>
|
|
<p>Beyond that, it can also be useful to provide implementations of <code>From</code> on your
|
|
error types. This allows you (the library author) and your users to
|
|
<a href="error-handling.html#composing-custom-error-types">compose more detailed errors</a>. For example,
|
|
<a href="http://burntsushi.net/rustdoc/csv/enum.Error.html"><code>csv::Error</code></a>
|
|
provides <code>From</code> impls for both <code>io::Error</code> and <code>byteorder::Error</code>.</p>
|
|
<p>Finally, depending on your tastes, you may also want to define a
|
|
<a href="error-handling.html#the-result-type-alias-idiom"><code>Result</code> type alias</a>, particularly if your
|
|
library defines a single error type. This is used in the standard library
|
|
for <a href="../../std/io/type.Result.html"><code>io::Result</code></a>
|
|
and <a href="../../std/fmt/type.Result.html"><code>fmt::Result</code></a>.</p>
|
|
<a class="header" href="error-handling.html#case-study-a-program-to-read-population-data" id="case-study-a-program-to-read-population-data"><h1>Case study: A program to read population data</h1></a>
|
|
<p>This section was long, and depending on your background, it might be
|
|
rather dense. While there is plenty of example code to go along with
|
|
the prose, most of it was specifically designed to be pedagogical. So,
|
|
we're going to do something new: a case study.</p>
|
|
<p>For this, we're going to build up a command line program that lets you
|
|
query world population data. The objective is simple: you give it a location
|
|
and it will tell you the population. Despite the simplicity, there is a lot
|
|
that can go wrong!</p>
|
|
<p>The data we'll be using comes from the <a href="https://github.com/petewarden/dstkdata">Data Science
|
|
Toolkit</a>. I've prepared some data from it for this exercise. You
|
|
can either grab the <a href="http://burntsushi.net/stuff/worldcitiespop.csv.gz">world population data</a> (41MB gzip compressed,
|
|
145MB uncompressed) or only the <a href="http://burntsushi.net/stuff/uscitiespop.csv.gz">US population data</a> (2.2MB gzip
|
|
compressed, 7.2MB uncompressed).</p>
|
|
<p>Up until now, we've kept the code limited to Rust's standard library. For a real
|
|
task like this though, we'll want to at least use something to parse CSV data,
|
|
parse the program arguments and decode that stuff into Rust types automatically. For that, we'll use the
|
|
<a href="https://crates.io/crates/csv"><code>csv</code></a>,
|
|
and <a href="https://crates.io/crates/rustc-serialize"><code>rustc-serialize</code></a> crates.</p>
|
|
<a class="header" href="error-handling.html#initial-setup" id="initial-setup"><h2>Initial setup</h2></a>
|
|
<p>We're not going to spend a lot of time on setting up a project with
|
|
Cargo because it is already covered well in <a href="getting-started.html#hello-cargo">the Cargo
|
|
section</a> and <a href="http://doc.crates.io/guide.html">Cargo's documentation</a>.</p>
|
|
<p>To get started from scratch, run <code>cargo new --bin city-pop</code> and make sure your
|
|
<code>Cargo.toml</code> looks something like this:</p>
|
|
<pre><code class="language-text">[package]
|
|
name = "city-pop"
|
|
version = "0.1.0"
|
|
authors = ["Andrew Gallant <jamslam@gmail.com>"]
|
|
|
|
[[bin]]
|
|
name = "city-pop"
|
|
|
|
[dependencies]
|
|
csv = "0.*"
|
|
rustc-serialize = "0.*"
|
|
getopts = "0.*"
|
|
</code></pre>
|
|
<p>You should already be able to run:</p>
|
|
<pre><code class="language-text">cargo build --release
|
|
./target/release/city-pop
|
|
# Outputs: Hello, world!
|
|
</code></pre>
|
|
<a class="header" href="error-handling.html#argument-parsing" id="argument-parsing"><h2>Argument parsing</h2></a>
|
|
<p>Let's get argument parsing out of the way. We won't go into too much
|
|
detail on Getopts, but there is <a href="http://doc.rust-lang.org/getopts/getopts/index.html">some good documentation</a>
|
|
describing it. The short story is that Getopts generates an argument
|
|
parser and a help message from a vector of options (The fact that it
|
|
is a vector is hidden behind a struct and a set of methods). Once the
|
|
parsing is done, the parser returns a struct that records matches
|
|
for defined options, and remaining "free" arguments.
|
|
From there, we can get information about the flags, for
|
|
instance, whether they were passed in, and what arguments they
|
|
had. Here's our program with the appropriate <code>extern crate</code>
|
|
statements, and the basic argument setup for Getopts:</p>
|
|
<pre><code class="language-rust ignore">extern crate getopts;
|
|
extern crate rustc_serialize;
|
|
|
|
use getopts::Options;
|
|
use std::env;
|
|
|
|
fn print_usage(program: &str, opts: Options) {
|
|
println!("{}", opts.usage(&format!("Usage: {} [options] <data-path> <city>", program)));
|
|
}
|
|
|
|
fn main() {
|
|
let args: Vec<String> = env::args().collect();
|
|
let program = &args[0];
|
|
|
|
let mut opts = Options::new();
|
|
opts.optflag("h", "help", "Show this usage message.");
|
|
|
|
let matches = match opts.parse(&args[1..]) {
|
|
Ok(m) => { m }
|
|
Err(e) => { panic!(e.to_string()) }
|
|
};
|
|
if matches.opt_present("h") {
|
|
print_usage(&program, opts);
|
|
return;
|
|
}
|
|
let data_path = &matches.free[0];
|
|
let city: &str = &matches.free[1];
|
|
|
|
// Do stuff with information.
|
|
}
|
|
</code></pre>
|
|
<p>First, we get a vector of the arguments passed into our program. We
|
|
then store the first one, knowing that it is our program's name. Once
|
|
that's done, we set up our argument flags, in this case a simplistic
|
|
help message flag. Once we have the argument flags set up, we use
|
|
<code>Options.parse</code> to parse the argument vector (starting from index one,
|
|
because index 0 is the program name). If this was successful, we
|
|
assign matches to the parsed object, if not, we panic. Once past that,
|
|
we test if the user passed in the help flag, and if so print the usage
|
|
message. The option help messages are constructed by Getopts, so all
|
|
we have to do to print the usage message is tell it what we want it to
|
|
print for the program name and template. If the user has not passed in
|
|
the help flag, we assign the proper variables to their corresponding
|
|
arguments.</p>
|
|
<a class="header" href="error-handling.html#writing-the-logic" id="writing-the-logic"><h2>Writing the logic</h2></a>
|
|
<p>We all write code differently, but error handling is usually the last thing we
|
|
want to think about. This isn't great for the overall design of a program, but
|
|
it can be useful for rapid prototyping. Because Rust forces us to be explicit
|
|
about error handling (by making us call <code>unwrap</code>), it is easy to see which
|
|
parts of our program can cause errors.</p>
|
|
<p>In this case study, the logic is really simple. All we need to do is parse the
|
|
CSV data given to us and print out a field in matching rows. Let's do it. (Make
|
|
sure to add <code>extern crate csv;</code> to the top of your file.)</p>
|
|
<pre><code class="language-rust ignore">use std::fs::File;
|
|
|
|
// This struct represents the data in each row of the CSV file.
|
|
// Type based decoding absolves us of a lot of the nitty gritty error
|
|
// handling, like parsing strings as integers or floats.
|
|
#[derive(Debug, RustcDecodable)]
|
|
struct Row {
|
|
country: String,
|
|
city: String,
|
|
accent_city: String,
|
|
region: String,
|
|
|
|
// Not every row has data for the population, latitude or longitude!
|
|
// So we express them as `Option` types, which admits the possibility of
|
|
// absence. The CSV parser will fill in the correct value for us.
|
|
population: Option<u64>,
|
|
latitude: Option<f64>,
|
|
longitude: Option<f64>,
|
|
}
|
|
|
|
fn print_usage(program: &str, opts: Options) {
|
|
println!("{}", opts.usage(&format!("Usage: {} [options] <data-path> <city>", program)));
|
|
}
|
|
|
|
fn main() {
|
|
let args: Vec<String> = env::args().collect();
|
|
let program = &args[0];
|
|
|
|
let mut opts = Options::new();
|
|
opts.optflag("h", "help", "Show this usage message.");
|
|
|
|
let matches = match opts.parse(&args[1..]) {
|
|
Ok(m) => { m }
|
|
Err(e) => { panic!(e.to_string()) }
|
|
};
|
|
|
|
if matches.opt_present("h") {
|
|
print_usage(&program, opts);
|
|
return;
|
|
}
|
|
|
|
let data_path = &matches.free[0];
|
|
let city: &str = &matches.free[1];
|
|
|
|
let file = File::open(data_path).unwrap();
|
|
let mut rdr = csv::Reader::from_reader(file);
|
|
|
|
for row in rdr.decode::<Row>() {
|
|
let row = row.unwrap();
|
|
|
|
if row.city == city {
|
|
println!("{}, {}: {:?}",
|
|
row.city, row.country,
|
|
row.population.expect("population count"));
|
|
}
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>Let's outline the errors. We can start with the obvious: the three places that
|
|
<code>unwrap</code> is called:</p>
|
|
<ol>
|
|
<li><a href="../../std/fs/struct.File.html#method.open"><code>File::open</code></a>
|
|
can return an
|
|
<a href="../../std/io/struct.Error.html"><code>io::Error</code></a>.</li>
|
|
<li><a href="http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.decode"><code>csv::Reader::decode</code></a>
|
|
decodes one record at a time, and
|
|
<a href="http://burntsushi.net/rustdoc/csv/struct.DecodedRecords.html">decoding a
|
|
record</a>
|
|
(look at the <code>Item</code> associated type on the <code>Iterator</code> impl)
|
|
can produce a
|
|
<a href="http://burntsushi.net/rustdoc/csv/enum.Error.html"><code>csv::Error</code></a>.</li>
|
|
<li>If <code>row.population</code> is <code>None</code>, then calling <code>expect</code> will panic.</li>
|
|
</ol>
|
|
<p>Are there any others? What if we can't find a matching city? Tools like <code>grep</code>
|
|
will return an error code, so we probably should too. So we have logic errors
|
|
specific to our problem, IO errors and CSV parsing errors. We're going to
|
|
explore two different ways to approach handling these errors.</p>
|
|
<p>I'd like to start with <code>Box<Error></code>. Later, we'll see how defining our own
|
|
error type can be useful.</p>
|
|
<a class="header" href="error-handling.html#error-handling-with-boxerror" id="error-handling-with-boxerror"><h2>Error handling with <code>Box<Error></code></h2></a>
|
|
<p><code>Box<Error></code> is nice because it <em>just works</em>. You don't need to define your own
|
|
error types and you don't need any <code>From</code> implementations. The downside is that
|
|
since <code>Box<Error></code> is a trait object, it <em>erases the type</em>, which means the
|
|
compiler can no longer reason about its underlying type.</p>
|
|
<p><a href="error-handling.html#the-limits-of-combinators">Previously</a> we started refactoring our code by
|
|
changing the type of our function from <code>T</code> to <code>Result<T, OurErrorType></code>. In
|
|
this case, <code>OurErrorType</code> is only <code>Box<Error></code>. But what's <code>T</code>? And can we add
|
|
a return type to <code>main</code>?</p>
|
|
<p>The answer to the second question is no, we can't. That means we'll need to
|
|
write a new function. But what is <code>T</code>? The simplest thing we can do is to
|
|
return a list of matching <code>Row</code> values as a <code>Vec<Row></code>. (Better code would
|
|
return an iterator, but that is left as an exercise to the reader.)</p>
|
|
<p>Let's refactor our code into its own function, but keep the calls to <code>unwrap</code>.
|
|
Note that we opt to handle the possibility of a missing population count by
|
|
simply ignoring that row.</p>
|
|
<pre><code class="language-rust ignore">use std::path::Path;
|
|
|
|
struct Row {
|
|
// This struct remains unchanged.
|
|
}
|
|
|
|
struct PopulationCount {
|
|
city: String,
|
|
country: String,
|
|
// This is no longer an `Option` because values of this type are only
|
|
// constructed if they have a population count.
|
|
count: u64,
|
|
}
|
|
|
|
fn print_usage(program: &str, opts: Options) {
|
|
println!("{}", opts.usage(&format!("Usage: {} [options] <data-path> <city>", program)));
|
|
}
|
|
|
|
fn search<P: AsRef<Path>>(file_path: P, city: &str) -> Vec<PopulationCount> {
|
|
let mut found = vec![];
|
|
let file = File::open(file_path).unwrap();
|
|
let mut rdr = csv::Reader::from_reader(file);
|
|
for row in rdr.decode::<Row>() {
|
|
let row = row.unwrap();
|
|
match row.population {
|
|
None => { } // Skip it.
|
|
Some(count) => if row.city == city {
|
|
found.push(PopulationCount {
|
|
city: row.city,
|
|
country: row.country,
|
|
count: count,
|
|
});
|
|
},
|
|
}
|
|
}
|
|
found
|
|
}
|
|
|
|
fn main() {
|
|
let args: Vec<String> = env::args().collect();
|
|
let program = &args[0];
|
|
|
|
let mut opts = Options::new();
|
|
opts.optflag("h", "help", "Show this usage message.");
|
|
|
|
let matches = match opts.parse(&args[1..]) {
|
|
Ok(m) => { m }
|
|
Err(e) => { panic!(e.to_string()) }
|
|
};
|
|
|
|
if matches.opt_present("h") {
|
|
print_usage(&program, opts);
|
|
return;
|
|
}
|
|
|
|
let data_path = &matches.free[0];
|
|
let city: &str = &matches.free[1];
|
|
|
|
for pop in search(data_path, city) {
|
|
println!("{}, {}: {:?}", pop.city, pop.country, pop.count);
|
|
}
|
|
}
|
|
|
|
</code></pre>
|
|
<p>While we got rid of one use of <code>expect</code> (which is a nicer variant of <code>unwrap</code>),
|
|
we still should handle the absence of any search results.</p>
|
|
<p>To convert this to proper error handling, we need to do the following:</p>
|
|
<ol>
|
|
<li>Change the return type of <code>search</code> to be <code>Result<Vec<PopulationCount>, Box<Error>></code>.</li>
|
|
<li>Use the <a href="error-handling.html#code-try-def"><code>try!</code> macro</a> so that errors are returned to the
|
|
caller instead of panicking the program.</li>
|
|
<li>Handle the error in <code>main</code>.</li>
|
|
</ol>
|
|
<p>Let's try it:</p>
|
|
<pre><code class="language-rust ignore">use std::error::Error;
|
|
|
|
// The rest of the code before this is unchanged.
|
|
|
|
fn search<P: AsRef<Path>>
|
|
(file_path: P, city: &str)
|
|
-> Result<Vec<PopulationCount>, Box<Error>> {
|
|
let mut found = vec![];
|
|
let file = try!(File::open(file_path));
|
|
let mut rdr = csv::Reader::from_reader(file);
|
|
for row in rdr.decode::<Row>() {
|
|
let row = try!(row);
|
|
match row.population {
|
|
None => { } // Skip it.
|
|
Some(count) => if row.city == city {
|
|
found.push(PopulationCount {
|
|
city: row.city,
|
|
country: row.country,
|
|
count: count,
|
|
});
|
|
},
|
|
}
|
|
}
|
|
if found.is_empty() {
|
|
Err(From::from("No matching cities with a population were found."))
|
|
} else {
|
|
Ok(found)
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>Instead of <code>x.unwrap()</code>, we now have <code>try!(x)</code>. Since our function returns a
|
|
<code>Result<T, E></code>, the <code>try!</code> macro will return early from the function if an
|
|
error occurs.</p>
|
|
<p>At the end of <code>search</code> we also convert a plain string to an error type
|
|
by using the <a href="../../std/convert/trait.From.html">corresponding <code>From</code> impls</a>:</p>
|
|
<pre><code class="language-rust ignore">// We are making use of this impl in the code above, since we call `From::from`
|
|
// on a `&'static str`.
|
|
impl<'a> From<&'a str> for Box<Error>
|
|
|
|
// But this is also useful when you need to allocate a new string for an
|
|
// error message, usually with `format!`.
|
|
impl From<String> for Box<Error>
|
|
</code></pre>
|
|
<p>Since <code>search</code> now returns a <code>Result<T, E></code>, <code>main</code> should use case analysis
|
|
when calling <code>search</code>:</p>
|
|
<pre><code class="language-rust ignore">...
|
|
match search(data_path, city) {
|
|
Ok(pops) => {
|
|
for pop in pops {
|
|
println!("{}, {}: {:?}", pop.city, pop.country, pop.count);
|
|
}
|
|
}
|
|
Err(err) => println!("{}", err)
|
|
}
|
|
...
|
|
</code></pre>
|
|
<p>Now that we've seen how to do proper error handling with <code>Box<Error></code>, let's
|
|
try a different approach with our own custom error type. But first, let's take
|
|
a quick break from error handling and add support for reading from <code>stdin</code>.</p>
|
|
<a class="header" href="error-handling.html#reading-from-stdin" id="reading-from-stdin"><h2>Reading from stdin</h2></a>
|
|
<p>In our program, we accept a single file for input and do one pass over the
|
|
data. This means we probably should be able to accept input on stdin. But maybe
|
|
we like the current format too—so let's have both!</p>
|
|
<p>Adding support for stdin is actually quite easy. There are only three things we
|
|
have to do:</p>
|
|
<ol>
|
|
<li>Tweak the program arguments so that a single parameter—the
|
|
city—can be accepted while the population data is read from stdin.</li>
|
|
<li>Modify the program so that an option <code>-f</code> can take the file, if it
|
|
is not passed into stdin.</li>
|
|
<li>Modify the <code>search</code> function to take an <em>optional</em> file path. When <code>None</code>,
|
|
it should know to read from stdin.</li>
|
|
</ol>
|
|
<p>First, here's the new usage:</p>
|
|
<pre><code class="language-rust ignore">fn print_usage(program: &str, opts: Options) {
|
|
println!("{}", opts.usage(&format!("Usage: {} [options] <city>", program)));
|
|
}
|
|
</code></pre>
|
|
<p>Of course we need to adapt the argument handling code:</p>
|
|
<pre><code class="language-rust ignore">...
|
|
let mut opts = Options::new();
|
|
opts.optopt("f", "file", "Choose an input file, instead of using STDIN.", "NAME");
|
|
opts.optflag("h", "help", "Show this usage message.");
|
|
...
|
|
let data_path = matches.opt_str("f");
|
|
|
|
let city = if !matches.free.is_empty() {
|
|
&matches.free[0]
|
|
} else {
|
|
print_usage(&program, opts);
|
|
return;
|
|
};
|
|
|
|
match search(&data_path, city) {
|
|
Ok(pops) => {
|
|
for pop in pops {
|
|
println!("{}, {}: {:?}", pop.city, pop.country, pop.count);
|
|
}
|
|
}
|
|
Err(err) => println!("{}", err)
|
|
}
|
|
...
|
|
</code></pre>
|
|
<p>We've made the user experience a bit nicer by showing the usage message,
|
|
instead of a panic from an out-of-bounds index, when <code>city</code>, the
|
|
remaining free argument, is not present.</p>
|
|
<p>Modifying <code>search</code> is slightly trickier. The <code>csv</code> crate can build a
|
|
parser out of
|
|
<a href="http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.from_reader">any type that implements <code>io::Read</code></a>.
|
|
But how can we use the same code over both types? There's actually a
|
|
couple ways we could go about this. One way is to write <code>search</code> such
|
|
that it is generic on some type parameter <code>R</code> that satisfies
|
|
<code>io::Read</code>. Another way is to use trait objects:</p>
|
|
<pre><code class="language-rust ignore">use std::io;
|
|
|
|
// The rest of the code before this is unchanged.
|
|
|
|
fn search<P: AsRef<Path>>
|
|
(file_path: &Option<P>, city: &str)
|
|
-> Result<Vec<PopulationCount>, Box<Error>> {
|
|
let mut found = vec![];
|
|
let input: Box<io::Read> = match *file_path {
|
|
None => Box::new(io::stdin()),
|
|
Some(ref file_path) => Box::new(try!(File::open(file_path))),
|
|
};
|
|
let mut rdr = csv::Reader::from_reader(input);
|
|
// The rest remains unchanged!
|
|
}
|
|
</code></pre>
|
|
<a class="header" href="error-handling.html#error-handling-with-a-custom-type" id="error-handling-with-a-custom-type"><h2>Error handling with a custom type</h2></a>
|
|
<p>Previously, we learned how to
|
|
<a href="error-handling.html#composing-custom-error-types">compose errors using a custom error type</a>.
|
|
We did this by defining our error type as an <code>enum</code> and implementing <code>Error</code>
|
|
and <code>From</code>.</p>
|
|
<p>Since we have three distinct errors (IO, CSV parsing and not found), let's
|
|
define an <code>enum</code> with three variants:</p>
|
|
<pre><code class="language-rust ignore">#[derive(Debug)]
|
|
enum CliError {
|
|
Io(io::Error),
|
|
Csv(csv::Error),
|
|
NotFound,
|
|
}
|
|
</code></pre>
|
|
<p>And now for impls on <code>Display</code> and <code>Error</code>:</p>
|
|
<pre><code class="language-rust ignore">use std::fmt;
|
|
|
|
impl fmt::Display for CliError {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match *self {
|
|
CliError::Io(ref err) => err.fmt(f),
|
|
CliError::Csv(ref err) => err.fmt(f),
|
|
CliError::NotFound => write!(f, "No matching cities with a \
|
|
population were found."),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for CliError {
|
|
fn description(&self) -> &str {
|
|
match *self {
|
|
CliError::Io(ref err) => err.description(),
|
|
CliError::Csv(ref err) => err.description(),
|
|
CliError::NotFound => "not found",
|
|
}
|
|
}
|
|
|
|
fn cause(&self) -> Option<&Error> {
|
|
match *self {
|
|
CliError::Io(ref err) => Some(err),
|
|
CliError::Csv(ref err) => Some(err),
|
|
// Our custom error doesn't have an underlying cause,
|
|
// but we could modify it so that it does.
|
|
CliError::NotFound => None,
|
|
}
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>Before we can use our <code>CliError</code> type in our <code>search</code> function, we need to
|
|
provide a couple <code>From</code> impls. How do we know which impls to provide? Well,
|
|
we'll need to convert from both <code>io::Error</code> and <code>csv::Error</code> to <code>CliError</code>.
|
|
Those are the only external errors, so we'll only need two <code>From</code> impls for
|
|
now:</p>
|
|
<pre><code class="language-rust ignore">impl From<io::Error> for CliError {
|
|
fn from(err: io::Error) -> CliError {
|
|
CliError::Io(err)
|
|
}
|
|
}
|
|
|
|
impl From<csv::Error> for CliError {
|
|
fn from(err: csv::Error) -> CliError {
|
|
CliError::Csv(err)
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>The <code>From</code> impls are important because of how
|
|
<a href="error-handling.html#code-try-def"><code>try!</code> is defined</a>. In particular, if an error occurs,
|
|
<code>From::from</code> is called on the error, which in this case, will convert it to our
|
|
own error type <code>CliError</code>.</p>
|
|
<p>With the <code>From</code> impls done, we only need to make two small tweaks to our
|
|
<code>search</code> function: the return type and the “not found” error. Here it is in
|
|
full:</p>
|
|
<pre><code class="language-rust ignore">fn search<P: AsRef<Path>>
|
|
(file_path: &Option<P>, city: &str)
|
|
-> Result<Vec<PopulationCount>, CliError> {
|
|
let mut found = vec![];
|
|
let input: Box<io::Read> = match *file_path {
|
|
None => Box::new(io::stdin()),
|
|
Some(ref file_path) => Box::new(try!(File::open(file_path))),
|
|
};
|
|
let mut rdr = csv::Reader::from_reader(input);
|
|
for row in rdr.decode::<Row>() {
|
|
let row = try!(row);
|
|
match row.population {
|
|
None => { } // Skip it.
|
|
Some(count) => if row.city == city {
|
|
found.push(PopulationCount {
|
|
city: row.city,
|
|
country: row.country,
|
|
count: count,
|
|
});
|
|
},
|
|
}
|
|
}
|
|
if found.is_empty() {
|
|
Err(CliError::NotFound)
|
|
} else {
|
|
Ok(found)
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>No other changes are necessary.</p>
|
|
<a class="header" href="error-handling.html#adding-functionality" id="adding-functionality"><h2>Adding functionality</h2></a>
|
|
<p>Writing generic code is great, because generalizing stuff is cool, and
|
|
it can then be useful later. But sometimes, the juice isn't worth the
|
|
squeeze. Look at what we just did in the previous step:</p>
|
|
<ol>
|
|
<li>Defined a new error type.</li>
|
|
<li>Added impls for <code>Error</code>, <code>Display</code> and two for <code>From</code>.</li>
|
|
</ol>
|
|
<p>The big downside here is that our program didn't improve a whole lot.
|
|
There is quite a bit of overhead to representing errors with <code>enum</code>s,
|
|
especially in short programs like this.</p>
|
|
<p><em>One</em> useful aspect of using a custom error type like we've done here is that
|
|
the <code>main</code> function can now choose to handle errors differently. Previously,
|
|
with <code>Box<Error></code>, it didn't have much of a choice: just print the message.
|
|
We're still doing that here, but what if we wanted to, say, add a <code>--quiet</code>
|
|
flag? The <code>--quiet</code> flag should silence any verbose output.</p>
|
|
<p>Right now, if the program doesn't find a match, it will output a message saying
|
|
so. This can be a little clumsy, especially if you intend for the program to
|
|
be used in shell scripts.</p>
|
|
<p>So let's start by adding the flags. Like before, we need to tweak the usage
|
|
string and add a flag to the Option variable. Once we've done that, Getopts does the rest:</p>
|
|
<pre><code class="language-rust ignore">...
|
|
let mut opts = Options::new();
|
|
opts.optopt("f", "file", "Choose an input file, instead of using STDIN.", "NAME");
|
|
opts.optflag("h", "help", "Show this usage message.");
|
|
opts.optflag("q", "quiet", "Silences errors and warnings.");
|
|
...
|
|
</code></pre>
|
|
<p>Now we only need to implement our “quiet” functionality. This requires us to
|
|
tweak the case analysis in <code>main</code>:</p>
|
|
<pre><code class="language-rust ignore">use std::process;
|
|
...
|
|
match search(&data_path, city) {
|
|
Err(CliError::NotFound) if matches.opt_present("q") => process::exit(1),
|
|
Err(err) => panic!("{}", err),
|
|
Ok(pops) => for pop in pops {
|
|
println!("{}, {}: {:?}", pop.city, pop.country, pop.count);
|
|
}
|
|
}
|
|
...
|
|
</code></pre>
|
|
<p>Certainly, we don't want to be quiet if there was an IO error or if the data
|
|
failed to parse. Therefore, we use case analysis to check if the error type is
|
|
<code>NotFound</code> <em>and</em> if <code>--quiet</code> has been enabled. If the search failed, we still
|
|
quit with an exit code (following <code>grep</code>'s convention).</p>
|
|
<p>If we had stuck with <code>Box<Error></code>, then it would be pretty tricky to implement
|
|
the <code>--quiet</code> functionality.</p>
|
|
<p>This pretty much sums up our case study. From here, you should be ready to go
|
|
out into the world and write your own programs and libraries with proper error
|
|
handling.</p>
|
|
<a class="header" href="error-handling.html#the-short-story" id="the-short-story"><h1>The Short Story</h1></a>
|
|
<p>Since this section is long, it is useful to have a quick summary for error
|
|
handling in Rust. These are some good “rules of thumb." They are emphatically
|
|
<em>not</em> commandments. There are probably good reasons to break every one of these
|
|
heuristics!</p>
|
|
<ul>
|
|
<li>If you're writing short example code that would be overburdened by error
|
|
handling, it's probably fine to use <code>unwrap</code> (whether that's
|
|
<a href="../../std/result/enum.Result.html#method.unwrap"><code>Result::unwrap</code></a>,
|
|
<a href="../../std/option/enum.Option.html#method.unwrap"><code>Option::unwrap</code></a>
|
|
or preferably
|
|
<a href="../../std/option/enum.Option.html#method.expect"><code>Option::expect</code></a>).
|
|
Consumers of your code should know to use proper error handling. (If they
|
|
don't, send them here!)</li>
|
|
<li>If you're writing a quick 'n' dirty program, don't feel ashamed if you use
|
|
<code>unwrap</code>. Be warned: if it winds up in someone else's hands, don't be
|
|
surprised if they are agitated by poor error messages!</li>
|
|
<li>If you're writing a quick 'n' dirty program and feel ashamed about panicking
|
|
anyway, then use either a <code>String</code> or a <code>Box<Error></code> for your
|
|
error type.</li>
|
|
<li>Otherwise, in a program, define your own error types with appropriate
|
|
<a href="../../std/convert/trait.From.html"><code>From</code></a>
|
|
and
|
|
<a href="../../std/error/trait.Error.html"><code>Error</code></a>
|
|
impls to make the <a href="../../std/macro.try.html"><code>try!</code></a>
|
|
macro more ergonomic.</li>
|
|
<li>If you're writing a library and your code can produce errors, define your own
|
|
error type and implement the
|
|
<a href="../../std/error/trait.Error.html"><code>std::error::Error</code></a>
|
|
trait. Where appropriate, implement
|
|
<a href="../../std/convert/trait.From.html"><code>From</code></a> to make both
|
|
your library code and the caller's code easier to write. (Because of Rust's
|
|
coherence rules, callers will not be able to impl <code>From</code> on your error type,
|
|
so your library should do it.)</li>
|
|
<li>Learn the combinators defined on
|
|
<a href="../../std/option/enum.Option.html"><code>Option</code></a>
|
|
and
|
|
<a href="../../std/result/enum.Result.html"><code>Result</code></a>.
|
|
Using them exclusively can be a bit tiring at times, but I've personally
|
|
found a healthy mix of <code>try!</code> and combinators to be quite appealing.
|
|
<code>and_then</code>, <code>map</code> and <code>unwrap_or</code> are my favorites.</li>
|
|
</ul>
|
|
|
|
</div>
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
<a href="concurrency.html" class="mobile-nav-chapters previous">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
|
|
|
|
<a href="choosing-your-guarantees.html" class="mobile-nav-chapters next">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<a href="concurrency.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
|
|
|
|
<a href="choosing-your-guarantees.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<!-- Local fallback for Font Awesome -->
|
|
<script>
|
|
if ($(".fa").css("font-family") !== "FontAwesome") {
|
|
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
|
}
|
|
</script>
|
|
|
|
<!-- Livereload script (if served using the cli tool) -->
|
|
|
|
|
|
<script src="highlight.js"></script>
|
|
<script src="book.js"></script>
|
|
</body>
|
|
</html>
|