vtx_sdk/
error.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4/// 插件运行时错误类型(统一错误模型)
5///
6/// 定义插件在运行过程中可能出现的所有已知错误。
7/// 所有错误均支持序列化,可用于 HTTP 返回或日志透传。
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub enum VtxError {
10    /// 底层数据库错误(如 SQL 执行失败、约束冲突等)
11    DatabaseError(String),
12
13    /// 序列化或反序列化失败(如 JSON 格式不匹配)
14    SerializationError(String),
15
16    /// 身份验证失败(带建议返回的 HTTP 状态码,如 401 / 403)
17    AuthDenied(u16),
18
19    /// 权限不足(如在只读环境尝试执行写操作)
20    PermissionDenied(String),
21
22    /// 资源不存在(如文件、视频、用户未找到等)
23    NotFound(String),
24
25    /// 插件内部逻辑错误(兜底类型)
26    Internal(String),
27}
28
29impl VtxError {
30    /// 将宿主侧返回的 `string` 错误消息做一个尽量合理的分类映射。
31    pub fn from_host_message(message: impl Into<String>) -> Self {
32        let msg = message.into();
33        let lower = msg.to_lowercase();
34
35        if lower.contains("permission denied") {
36            return VtxError::PermissionDenied(msg);
37        }
38
39        if lower.contains("uuid not found") || lower.contains("not found") {
40            return VtxError::NotFound(msg);
41        }
42
43        VtxError::Internal(msg)
44    }
45}
46
47impl fmt::Display for VtxError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            VtxError::DatabaseError(msg) => write!(f, "Database error: {}", msg),
51            VtxError::SerializationError(msg) => write!(f, "Data serialization error: {}", msg),
52            VtxError::AuthDenied(code) => write!(f, "Authentication denied (Code: {})", code),
53            VtxError::PermissionDenied(msg) => write!(f, "Permission denied: {}", msg),
54            VtxError::NotFound(msg) => write!(f, "Resource not found: {}", msg),
55            VtxError::Internal(msg) => write!(f, "Internal error: {}", msg),
56        }
57    }
58}
59
60impl std::error::Error for VtxError {}
61
62/// 插件标准结果类型别名
63///
64/// 推荐用于所有返回 VtxError 的接口中,确保错误链统一。
65pub type VtxResult<T> = Result<T, VtxError>;