| 1 | #[derive(thiserror::Error, Debug)] |
| 2 | pub enum AppError { |
| 3 | #[error("Not found")] |
| 4 | NotFound, |
| 5 | #[error("Not signed in or invalid credentials")] |
| 6 | Unauthorized, |
| 7 | #[error("You don't have permission to do that")] |
| 8 | Forbidden, |
| 9 | #[error("{0}")] |
| 10 | Conflict(String), |
| 11 | #[error("{0}")] |
| 12 | Validation(String), |
| 13 | /// 带稳定 code 的校验错误。**message 仍是英文原句**——它是给不做本地化的 |
| 14 | /// 客户端(MCP、CLI)与日志用的;界面拿 code 去 i18n 里查措辞。 |
| 15 | /// |
| 16 | /// 界面语言在客户端之后,后端不再拥有 locale(见 docs/decisions/0004), |
| 17 | /// 所以留在这里的字符串是永久英文。用户能撞到的都该带上 code。 |
| 18 | #[error("{message}")] |
| 19 | Invalid { |
| 20 | code: &'static str, |
| 21 | message: String, |
| 22 | /// 机器给的补充(cron 解析器的报错之类)。措辞归界面,细节归这里 |
| 23 | detail: Option<String>, |
| 24 | }, |
| 25 | #[error(transparent)] |
| 26 | Db(#[from] sqlx::Error), |
| 27 | #[error(transparent)] |
| 28 | Other(#[from] anyhow::Error), |
| 29 | } |
| 30 | |
| 31 | impl AppError { |
| 32 | pub fn invalid(code: &'static str, message: impl Into<String>) -> Self { |
| 33 | AppError::Invalid { |
| 34 | code, |
| 35 | message: message.into(), |
| 36 | detail: None, |
| 37 | } |
| 38 | } |
| 39 | pub fn invalid_detail( |
| 40 | code: &'static str, |
| 41 | message: impl Into<String>, |
| 42 | detail: impl Into<String>, |
| 43 | ) -> Self { |
| 44 | AppError::Invalid { |
| 45 | code, |
| 46 | message: message.into(), |
| 47 | detail: Some(detail.into()), |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub type AppResult<T> = Result<T, AppError>; |
| 53 | |
| 54 | /// 标在一个**不会因为重试而变好**的失败上(见 issue #195)。 |
| 55 | /// |
| 56 | /// 队列的默认假设是「再等一会儿也许就好了」,多数失败确实如此:端点抖一下、 |
| 57 | /// 数据库忙一瞬、限流一分钟就过去。余额耗尽不是——三次重试隔着 30 秒、2 分钟、 |
| 58 | /// 4 分半,七分钟里没有人会去充值,重试只是把同一句错误重说三遍,而运维需要 |
| 59 | /// 看见的那条「失败」被推迟了七分钟才出现。 |
| 60 | /// |
| 61 | /// **判据留在处理器那一侧,不在队列里。** 什么算没救跟领域有关—— |
| 62 | /// `utopia-store` 看不见 `utopia-llm` 的错误类型,也不该看见。处理器把这个标记 |
| 63 | /// 挂上去(`err.context(Terminal)`),队列只问「挂了没有」。 |
| 64 | /// |
| 65 | /// 挂上它不影响别的:告警照报(`observe_job_failure` 一并认这个标记, |
| 66 | /// 否则失败得更快反而没人被告知),`last_error` 照写。 |
| 67 | #[derive(Debug, Clone, Copy)] |
| 68 | pub struct Terminal; |
| 69 | |
| 70 | impl std::fmt::Display for Terminal { |
| 71 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 72 | f.write_str("will not recover by retrying") |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | impl std::error::Error for Terminal {} |
| 77 | |
| 78 | /// 这次失败被标成不必重试了吗。**沿整条 context 链找**——处理器挂上标记之后, |
| 79 | /// 上层还会继续 `context(...)`,只看最外层就等于没看 |
| 80 | pub fn is_terminal(err: &anyhow::Error) -> bool { |
| 81 | err.chain().any(|e| e.is::<Terminal>()) |
| 82 | } |