a little better error handling

This commit is contained in:
Darren Schroeder 2024-11-14 14:17:53 -06:00
parent 61345c48b4
commit bc9a230e5e

View File

@ -188,9 +188,11 @@ fn groups_to_table(
record_map.insert("count".to_string(), Value::int(items.len() as i64, span)); record_map.insert("count".to_string(), Value::int(items.len() as i64, span));
if let Some(sum_col) = maybe_sum_column.clone() { if let Some(sum_col) = maybe_sum_column.clone() {
let (sum_col_name, sum) = sum_celllpath(sum_col, &items, span, true); match sum_celllpath(sum_col, &items, span) {
Ok((sum_col_name, sum)) => {
// add sum // add sum
record_map.insert(sum_col_name.clone() + "_sum", Value::float(sum, span)); record_map
.insert(sum_col_name.clone() + "_sum", Value::float(sum, span));
let avg = if !items.is_empty() { let avg = if !items.is_empty() {
sum / items.len() as f64 sum / items.len() as f64
} else { } else {
@ -199,6 +201,12 @@ fn groups_to_table(
// add avg // add avg
record_map.insert(sum_col_name + "_avg", Value::float(avg, span)); record_map.insert(sum_col_name + "_avg", Value::float(avg, span));
} }
Err(err) => {
// It seems a little odd to be adding an error to the record
record_map.insert("error".to_string(), Value::error(err, span));
}
}
}
Value::record(record_map, span) Value::record(record_map, span)
}) })
@ -207,7 +215,7 @@ fn groups_to_table(
) )
} }
fn sum_celllpath(column: Value, items: &[Value], span: Span, is_sum: bool) -> (String, f64) { fn sum_celllpath(column: Value, items: &[Value], span: Span) -> Result<(String, f64), ShellError> {
if let Value::CellPath { val, .. } = column { if let Value::CellPath { val, .. } = column {
let sum: f64 = items let sum: f64 = items
.iter() .iter()
@ -219,14 +227,12 @@ fn sum_celllpath(column: Value, items: &[Value], span: Span, is_sum: bool) -> (S
.unwrap_or(0.0) .unwrap_or(0.0)
}) })
.sum(); .sum();
(val.to_column_name(), sum) Ok((val.to_column_name(), sum))
} else { } else {
eprintln!("sum_col type: {:#?}", column.get_type()); Err(ShellError::TypeMismatch {
if is_sum { err_message: format!("Only CellPath's are allowed. Found {}.", column.get_type()),
("sum".to_string(), 0.0f64) span,
} else { })
("avg".to_string(), 0.0f64)
}
} }
} }