Skip to content

Commit

Permalink
Add better error handling in the Rust 2.0 number format (unicode-org#365
Browse files Browse the repository at this point in the history
)
  • Loading branch information
sffc authored Dec 19, 2024
1 parent 9619804 commit 69fa803
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 18 deletions.
4 changes: 4 additions & 0 deletions executors/rust/2.0-beta1/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ mod numberfmt;
mod pluralrules;
mod relativedatetime_fmt;

#[path = "../../common/try_or_return_error.rs"]
#[macro_use]
mod try_or_return_error;

pub fn return_error(json_obj: &serde_json::Value) -> Result<serde_json::Value, String> {
let label = &json_obj["label"].as_str().unwrap();
return Ok(serde_json::json!({
Expand Down
29 changes: 11 additions & 18 deletions executors/rust/2.0-beta1/src/numberfmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,14 @@ pub fn run_numberformat_test(json_obj: &Value) -> Result<Value, String> {

let result_string = if is_compact {
// We saw compact!
let cdf = if compact_type == "short" {
CompactDecimalFormatter::try_new_short(langid.into(), Default::default()).unwrap()
} else {
println!("#{:?}", " LONG");
CompactDecimalFormatter::try_new_long(langid.into(), Default::default()).unwrap()
};
let cdf = crate::try_or_return_error!(label, langid, {
if compact_type == "short" {
CompactDecimalFormatter::try_new_short((&langid).into(), Default::default())
} else {
println!("#{:?}", " LONG");
CompactDecimalFormatter::try_new_long((&langid).into(), Default::default())
}
});
// input.parse().map_err(|e| e.to_string())?;

let input_num = input.parse::<FixedDecimal>().map_err(|e| e.to_string())?;
Expand All @@ -168,18 +170,9 @@ pub fn run_numberformat_test(json_obj: &Value) -> Result<Value, String> {
} else {
// FixedDecimal
// Can this fail with invalid options?
let fdf = match FixedDecimalFormatter::try_new((&langid).into(), options.clone()) {
Ok(fdf) => fdf,
Err(e) => {
let locale_str = langid.to_string();
return Ok(json!({
"label": label,
"locale_label": locale_str,
"error": e.to_string(),
"error_type": "panic",
}));
}
};
let fdf = crate::try_or_return_error!(label, langid, {
FixedDecimalFormatter::try_new((&langid).into(), options.clone())
});

// Apply relevant options for digits.
if let Some(x) = option_struct.maximum_fraction_digits {
Expand Down
16 changes: 16 additions & 0 deletions executors/rust/common/try_or_return_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#[macro_export]
macro_rules! try_or_return_error {
($label:expr, $locale:expr, $expr:expr) => {{
match ($expr) {
Ok(x) => x,
Err(e) => {
return Ok(json!({
"label": ($label),
"locale_label": ($locale).to_string(),
"error": e.to_string(),
"error_type": "panic",
}));
}
}
}};
}

0 comments on commit 69fa803

Please sign in to comment.