Skip to content

web search done right

better error handling in calculator widget

Mikkel Denker5c7278a271ca
diff --git a/crates/core/src/widgets/calculator.rs b/crates/core/src/widgets/calculator.rs
index 5d260032..3195fa24 100644
--- a/crates/core/src/widgets/calculator.rs
+++ b/crates/core/src/widgets/calculator.rs
@@ -191,21 +191,22 @@ impl Calculator {
return Err(Error::CalculatorParse);
}
- let result: String = res
- .get_main_result_spans()
- .map(|span| match span.kind() {
+ let mut result: String = String::new();
+
+ for span in res.get_main_result_spans() {
+ match span.kind() {
fend_core::SpanKind::Number => {
- let num = span.string().parse::<f64>().unwrap();
+ let num = span.string().parse::<f64>()?;
if num.fract() > 0.01 {
- format!("{:.2}", num)
+ result.push_str(format!("{:.2}", num).as_str());
} else {
- num.to_string()
+ result.push_str(num.to_string().as_str());
}
}
- _ => span.string().to_string(),
- })
- .collect();
+ _ => result.push_str(span.string()),
+ }
+ }
Ok(Calculation {
input: expr.to_string(),
diff --git a/crates/core/src/widgets/mod.rs b/crates/core/src/widgets/mod.rs
index 57d1d4d1..be9470bf 100644
--- a/crates/core/src/widgets/mod.rs
+++ b/crates/core/src/widgets/mod.rs
@@ -31,6 +31,9 @@ pub mod thesaurus;
pub enum Error {
#[error("Calculator parse")]
CalculatorParse,
+
+ #[error("Failed to parse float")]
+ FloatParse(#[from] std::num::ParseFloatError),
}
pub struct Widgets {