diff --git a/src/error-handling/error-contexts.md b/src/error-handling/error-contexts.md index dd216c8f..ae006e9b 100644 --- a/src/error-handling/error-contexts.md +++ b/src/error-handling/error-contexts.md @@ -7,14 +7,7 @@ custom error types: ```rust,editable,compile_fail use std::{fs, io}; use std::io::Read; -use thiserror::Error; -use anyhow::{Context, Result}; - -#[derive(Error, Debug)] -enum ReadUsernameError { - #[error("Found no username in {0}")] - EmptyUsername(String), -} +use anyhow::{Context, Result, bail}; fn read_username(path: &str) -> Result { let mut username = String::with_capacity(100); @@ -23,7 +16,7 @@ fn read_username(path: &str) -> Result { .read_to_string(&mut username) .context("Failed to read")?; if username.is_empty() { - return Err(ReadUsernameError::EmptyUsername(String::from(path)).into()); + bail!("Found no username in {path}"); } Ok(username) } @@ -39,7 +32,8 @@ fn main() {
-* `anyhow::Result` is generic and it can hold any `Error` implementation without changing the type signature. +* `anyhow::Result` is a type alias for `Result`. +* `anyhow::Error` is generic and it can hold any `Error` implementation without changing the type signature. * Actual error type inside of it can be extracted for examination if necessary. * Functionality provided by `anyhow::Result` may be familiar to Go developers, as it provides similar usage patterns and ergonomics of `(T, error)` from Go.