From 1b993478362a51cce6d782d4d9dfc0c5c03bbd5d Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 30 May 2022 20:35:00 -0400 Subject: [PATCH] Demonstrate a better expect message. Fixes #2918. --- .../no-listing-05-expect/src/main.rs | 3 ++- src/ch09-02-recoverable-errors-with-result.md | 20 ++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/listings/ch09-error-handling/no-listing-05-expect/src/main.rs b/listings/ch09-error-handling/no-listing-05-expect/src/main.rs index cab643bc5..3d36fa5b1 100644 --- a/listings/ch09-error-handling/no-listing-05-expect/src/main.rs +++ b/listings/ch09-error-handling/no-listing-05-expect/src/main.rs @@ -1,5 +1,6 @@ use std::fs::File; fn main() { - let f = File::open("hello.txt").expect("Failed to open hello.txt"); + let greeting_file = File::open("hello.txt") + .expect("hello.txt should be included in this project"); } diff --git a/src/ch09-02-recoverable-errors-with-result.md b/src/ch09-02-recoverable-errors-with-result.md index 4a4db2966..deb708f97 100644 --- a/src/ch09-02-recoverable-errors-with-result.md +++ b/src/ch09-02-recoverable-errors-with-result.md @@ -209,16 +209,22 @@ the `panic!` macro. The error message used by `expect` in its call to `panic!` will be the parameter that we pass to `expect`, rather than the default `panic!` message that `unwrap` uses. Here’s what it looks like: + + ```text -thread 'main' panicked at 'Failed to open hello.txt: Error { repr: Os { code: -2, message: "No such file or directory" } }', src/libcore/result.rs:906:4 +thread 'main' panicked at 'hello.txt should be included in this project: Error +{ repr: Os { code: 2, message: "No such file or directory" } }', +src/libcore/result.rs:906:4 ``` -Because this error message starts with the text we specified, `Failed to open -hello.txt`, it will be easier to find where in the code this error message is -coming from. If we use `unwrap` in multiple places, it can take more time to -figure out exactly which `unwrap` is causing the panic because all `unwrap` -calls that panic print the same message. +In production-quality code, most Rustaceans choose `expect` rather than +`unwrap` and give more context about why the operation is expected to always +succeed. That way, if your assumptions are ever proven wrong, you have more +information to use in debugging. ### Propagating Errors