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 <philipp.schuster@cyberus-technology.de> On-behalf-of: SAP philipp.schuster@sap.com
This commit is contained in:
parent
262984f8fc
commit
0e40a50407
3 changed files with 14 additions and 16 deletions
|
|
@ -3,3 +3,6 @@ authors = ["The Cloud Hypervisor Authors"]
|
|||
edition = "2021"
|
||||
name = "option_parser"
|
||||
version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
thiserror = "2.0.6"
|
||||
|
|
|
|||
|
|
@ -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<String, OptionParserValue>,
|
||||
|
|
@ -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<T> = std::result::Result<T, OptionParserError>;
|
||||
|
||||
fn split_commas(s: &str) -> OptionParserResult<Vec<String>> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue