| 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>; |