use std::collections::HashMap;
use sz_rust_http_facade::BaseException;
use sz_rust_state_facade::i18n::I18n;
pub fn localize_exception(ex: &BaseException, i18n: &I18n, lang: Option<&str>) -> String {
match ex.message_key() {
Some(key) => i18n
.get(key, &HashMap::new(), lang)
.unwrap_or_else(|| ex.msg.clone()),
None => ex.msg.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use sz_rust_http_facade::ErrorCode;
#[test]
fn localize_with_key_and_translation() {
let i18n = I18n::new();
i18n.set_default_lang("zh-cn");
i18n.set("zh-cn", "errors.not_login", "请先登录");
i18n.set("en", "errors.not_login", "Please sign in");
let err = BaseException::new(ErrorCode::NotLogin, "fallback")
.with_message_key("errors.not_login");
assert_eq!(localize_exception(&err, &i18n, None), "请先登录");
assert_eq!(
localize_exception(&err, &i18n, Some("en")),
"Please sign in"
);
}
#[test]
fn localize_with_key_missing_translation_falls_back_to_msg() {
let i18n = I18n::new();
i18n.set_default_lang("zh-cn");
let err = BaseException::new(ErrorCode::Forbidden, "无权限")
.with_message_key("errors.missing_key");
assert_eq!(localize_exception(&err, &i18n, None), "无权限");
}
#[test]
fn localize_without_key_returns_msg_as_is() {
let i18n = I18n::new();
i18n.set_default_lang("zh-cn");
let err = BaseException::failed("系统繁忙");
assert_eq!(localize_exception(&err, &i18n, None), "系统繁忙");
assert!(err.message_key().is_none());
}
}