use crate::ScoutError;
pub const NAME: &str = "Scout";
pub const SPECIES: &str = "检索机器人";
pub const TAGLINE: &str = "八个插槽,插哪个用哪个 —— 业务代码一行不改";
pub const ART: &str = r#" (*)
|
______________|______________
/ \
| [o] [o] |
|_____________________________|
| |
_________________| |_________________
/ \
| +-----+-----+-----+-----+ | [##]
| | ## | ## | ## | | |<- - - -'
\| +-----+-----+-----+-----+ |/
o| | ## | ## | ## | ## | |o
| +-----+-----+-----+-----+ |
\_____________________________________/
|| ||
_||_ _||_
(____) (____)"#;
pub fn banner() -> String {
format!("{ART}\n\n {NAME} · {SPECIES}\n {TAGLINE}\n")
}
pub fn hint(err: &ScoutError) -> &'static str {
match err {
ScoutError::InvalidIndexName(_) => {
"索引名里有空白、斜杠、通配符,或者以 `.` `-` `_` 开头 —— 这个槽位对不上,换一个名字试试?"
}
ScoutError::InvalidHost(_) => {
"host 里塞了 `user:pass@` —— 凭据别放 URL,请求一出错它就会跟着错误信息进日志。"
}
ScoutError::InvalidFieldName(_) => {
"字段名里有空格或运算符字符 —— 过滤表达式会被它改写成另一条查询,换个字段名。"
}
ScoutError::InvalidResult(_) => "文档字段得是 JSON 对象。我读到的是别的东西。",
ScoutError::Unsupported(_) => {
"这个后端我还没找到路 —— Cargo.toml 里对应的 feature 启用了吗?"
}
ScoutError::Json(_) => "JSON 没解析出来 —— 检查一下字段的类型和嵌套层级。",
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia"
))]
ScoutError::Http(_) => "连不上后端 —— 服务起来了吗?地址(host)和 API key 对吗?",
#[cfg(feature = "database")]
ScoutError::Sqlx(_) => "SQLite 那边出问题了 —— 看看 database.url 指向的库和表结构。",
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia",
feature = "xunsearch"
))]
ScoutError::Backend(_) => "后端拒绝了这次请求 —— 往上翻,它的原始错误信息里有线索。",
#[cfg(feature = "xunsearch")]
ScoutError::XunSearch(_) => {
"xunsearchd 回了个我看不懂的东西 —— 项目的 ini 字段方案和索引端一致吗?"
}
#[cfg(feature = "xunsearch")]
ScoutError::XunSearchIo(_) => {
"没连上 xunsearchd —— 它起来了吗?index/search 端口(8383 / 8384)通吗?"
}
}
}
pub fn format_error(err: &ScoutError) -> String {
format!("error: {err}\n\n [o_o] {NAME}:{}\n", hint(err))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn art_is_pure_ascii() {
assert!(ART.is_ascii(), "ASCII art must stay 7-bit");
assert!(banner().contains(NAME));
}
#[test]
fn hint_covers_every_error_variant() {
let cases = [
ScoutError::InvalidIndexName("a/b".into()),
ScoutError::InvalidHost("userinfo".into()),
ScoutError::InvalidFieldName("x:=1 || y".into()),
ScoutError::InvalidResult("not an object".into()),
ScoutError::Unsupported("no feature".into()),
ScoutError::Json(serde_json::from_str::<i32>("x").unwrap_err()),
];
for err in cases {
assert!(!hint(&err).is_empty(), "no robot hint for {err:?}");
assert!(format_error(&err).contains(NAME));
}
}
#[test]
fn format_error_keeps_the_original_message() {
let err = ScoutError::Unsupported("engine driver `xunsearch` requires its feature".into());
let text = format_error(&err);
assert!(text.contains("engine driver `xunsearch` requires its feature"));
assert!(text.contains("feature"));
}
}