From 27b6165202b22ecfdee4b8a984e97b49f1225ea6 Mon Sep 17 00:00:00 2001 From: Andrew Walbran Date: Mon, 16 Jan 2023 17:53:43 +0000 Subject: [PATCH] Implement Error. --- src/error-handling/converting-error-types.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/error-handling/converting-error-types.md b/src/error-handling/converting-error-types.md index 2f5aaf10..debac80d 100644 --- a/src/error-handling/converting-error-types.md +++ b/src/error-handling/converting-error-types.md @@ -19,8 +19,10 @@ The `From::from` call here means we attempt to convert the error type to the type returned by the function: ```rust,editable +use std::error::Error; use std::{fs, io}; use std::io::Read; +use std::fmt::{self, Display, Formatter}; #[derive(Debug)] enum ReadUsernameError { @@ -28,6 +30,17 @@ enum ReadUsernameError { EmptyUsername(String), } +impl Error for ReadUsernameError {} + +impl Display for ReadUsernameError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Self::IoError(e) => write!(f, "IO error: {}", e), + Self::EmptyUsername(filename) => write!(f, "Found no username in {}", filename), + } + } +} + impl From for ReadUsernameError { fn from(err: io::Error) -> ReadUsernameError { ReadUsernameError::IoError(err)