forked from hakimel/reveal.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2016_12_15_error_handling.html
400 lines (374 loc) · 17.1 KB
/
2016_12_15_error_handling.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Rust - Error Handling</title>
<meta name="author" content="Sascha Grunert">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/solarized.css">
<link rel="stylesheet" href="lib/css/zenburn.css">
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown>
<script type="text/template">
# Rust
## Error handling
<small>Third user group Meetup in Leipzig (2016-12-15)</small>
</script>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Basics
</script>
</section>
<section data-markdown>
<script type="text/template">
## Panic
- case analysis to determine whether a computation was successful or not
- one way could be to use `panic`, which will unwind the current task
```rust
// 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);
}
```
```bash
thread 'main' panicked at 'Invalid number: 11'
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Unwrapping
_Give me the result of the computation, and if there was an error, panic and stop the program._
```rust
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);
}
```
- mostly used by the `Option` and `Result` types
</script>
</section>
<section data-markdown>
<script type="text/template">
## Option type
- express the possibility of absence
```rust
enum Option<T> {
None,
Some(T),
}
```
```rust
// 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
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Option type
Supported pattern matching:
```rust
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..]),
}
}
```
Unwrapping:
```rust
impl<T> Option<T> {
fn unwrap(self) -> T {
match self {
Option::Some(val) => val,
Option::None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
}
```
[Composing option types together is possible as well.](https://doc.rust-lang.org/std/option/enum.Option.html)
</script>
</section>
<section data-markdown>
<script type="text/template">
## Result type
- _richer_ version of an Option
- expresses the possibility of _error_
```rust
enum Result<T, E> {
Ok(T),
Err(E),
}
```
```rust
type Option<T> = Result<T, ()>;
```
```rust
impl<T, E: ::std::fmt::Debug> Result<T, E> {
fn unwrap(self) -> T {
match self {
Result::Ok(val) => val,
Result::Err(err) => panic!("{}", err),
}
}
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Result type
Parsing integer example:
```rust
impl str {
fn parse<F: FromStr>(&self) -> Result<F, F::Err>;
}
```
```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);
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Result type
Example with real error handling:
```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),
}
}
```
Type aliasing could make code a bit cleaner:
```rust
use std::num::ParseIntError;
use std::result;
type Result<T> = result::Result<T, ParseIntError>;
fn double_number(number_str: &str) -> Result<i32> {
unimplemented!();
}
```
[Converting and composing Option and Result possible](https://doc.rust-lang.org/std/option/enum.Option.html)
</script>
</section>
<section data-markdown>
<script type="text/template">
## Early returns
`?` Operator will help to keep code compact:
```rust
fn log_result(&self, record: &LogRecord) -> MyOwnResult<()> {
let mut t = stderr()
.ok_or(error("Term", "Could not create terminal"))?;
match record.level() {
LogLevel::Error => {
t.fg(RED)?;
write!(t, "[ERROR] ")?;
t.reset()?;
writeln!(t, "{}", record.args())?;
}
_ => {
writeln!(t, "[{}] {}", record.level(), record.args())?;
}
}
Ok(())
}
```
</script>
</section>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Error types
</script>
</section>
<section data-markdown>
<script type="text/template">
## Error trait
A standard library trait:
```rust
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 }
}
```
- Debug representation of the error
- user-facing Display representation of the error
- short description of the error
- Inspect the causal chain of an error
</script>
</section>
<section data-markdown>
<script type="text/template">
## Own error types
```rust
use std::io;
use std::num;
#[derive(Debug)]
enum CliError {
Io(io::Error),
Parse(num::ParseIntError),
}
```
```rust
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 {
CliError::Io(ref err) => Some(err),
CliError::Parse(ref err) => Some(err),
}
}
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Error conversion
- [`From`](https://doc.rust-lang.org/stable/std/convert/trait.From.html) trait can be implemented to convert errors
- `?` operator tries to convert errors as well
- simplest solution: `Box<Error>`
```rust
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 = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let n = contents.trim().parse::<i32>()?;
Ok(2 * n)
}
```
- using the trait object Error will cause loosing the underlying type
</script>
</section>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Best practices
</script>
</section>
<section data-markdown>
<script type="text/template">
## Short example code
- unwrap and expect would fit good
- `String` or `Box<Error>` idiomatic too
</script>
</section>
<section data-markdown>
<script type="text/template">
## Libraries
- introduce your own error types for libraries
- implement the Error trait for your type
- use combination of Option and Result
<br>
_Demo_
</script>
</section>
</section>
<section data-markdown>
<script type="text/template">
# Thank you!
</script>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
backgroundTransition: 'zoom',
center: true,
controls: true,
history: true,
progress: true,
transition: 'zoom',
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>