From 0e40a504077d53376bbcca34052df32175e47de5 Mon Sep 17 00:00:00 2001 From: Philipp Schuster Date: Mon, 19 May 2025 09:45:28 +0200 Subject: [PATCH] misc: option_parser: streamline #[source] and Error This streamlines the code base to follow best practices for error handling in Rust: Each error struct implements std::error::Error (most due via thiserror::Error derive macro) and sets its source accordingly. This allows future work that nicely prints the error chains, for example. So far, the convention is that each error prints its sub error as part of its Display::fmt() impl. Signed-off-by: Philipp Schuster On-behalf-of: SAP philipp.schuster@sap.com --- Cargo.lock | 3 +++ option_parser/Cargo.toml | 3 +++ option_parser/src/lib.rs | 24 ++++++++---------------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2090d36d2..b7af3e20e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1435,6 +1435,9 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "option_parser" version = "0.1.0" +dependencies = [ + "thiserror 2.0.6", +] [[package]] name = "ordered-stream" diff --git a/option_parser/Cargo.toml b/option_parser/Cargo.toml index 23fbd4752..fc3129a70 100644 --- a/option_parser/Cargo.toml +++ b/option_parser/Cargo.toml @@ -3,3 +3,6 @@ authors = ["The Cloud Hypervisor Authors"] edition = "2021" name = "option_parser" version = "0.1.0" + +[dependencies] +thiserror = "2.0.6" diff --git a/option_parser/src/lib.rs b/option_parser/src/lib.rs index 54f97ee29..2d4cce017 100644 --- a/option_parser/src/lib.rs +++ b/option_parser/src/lib.rs @@ -4,10 +4,11 @@ // use std::collections::HashMap; -use std::fmt; use std::num::ParseIntError; use std::str::FromStr; +use thiserror::Error; + #[derive(Default)] pub struct OptionParser { options: HashMap, @@ -18,26 +19,17 @@ struct OptionParserValue { requires_value: bool, } -#[derive(Debug)] +#[derive(Error, Debug)] pub enum OptionParserError { + #[error("unknown option: {0}")] UnknownOption(String), + #[error("unknown option: {0}")] InvalidSyntax(String), - Conversion(String, String), + #[error("unable to convert {1} for {0}")] + Conversion(String /* field */, String /* value */), + #[error("invalid value: {0}")] InvalidValue(String), } - -impl fmt::Display for OptionParserError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - OptionParserError::UnknownOption(s) => write!(f, "unknown option: {s}"), - OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{s}"), - OptionParserError::Conversion(field, value) => { - write!(f, "unable to convert {value} for {field}") - } - OptionParserError::InvalidValue(s) => write!(f, "invalid value: {s}"), - } - } -} type OptionParserResult = std::result::Result; fn split_commas(s: &str) -> OptionParserResult> {