Skip to main content

wordval_core/
api.rs

1//! 框架核心 API 类型:响应体、错误、分页数据、错误码
2//!
3//! 这些类型是框架的公共"语言",所有 crate 都依赖它们。
4//! `IntoResponse` 实现通过 `features = ["web"]` 开启。
5
6use crate::error_registry::{error_message_of, ErrorCode};
7use crate::Error;
8use serde::Serialize;
9use std::borrow::Cow;
10
11#[cfg(feature = "axum")]
12use axum::{
13    http::StatusCode,
14    response::{IntoResponse, Json},
15};
16
17// ──── 错误码常量 ────────────────────────────────────
18
19/// 业务码体系:`code == HTTP status` 为通用 HTTP 语义;`code = status*100 + 序号`
20/// (如 `RECORD_NOT_FOUND` = 40401)为业务细分子码——HTTP 层语义不变,前端可按
21/// `code` 精确区分同一 HTTP 状态下的不同业务情形。
22pub mod codes {
23    pub const OK: i32 = 200;
24    pub const BAD_REQUEST: i32 = 400;
25    pub const UNAUTHORIZED: i32 = 401;
26    pub const FORBIDDEN: i32 = 403;
27    pub const NOT_FOUND: i32 = 404;
28    /// 记录不存在(数据级 404 子码):`Q::one`/`Q::one_as` 空结果等
29    /// 「目标记录理应存在却缺失」的情形,区别于路由/寻址级的 [`NOT_FOUND`]。
30    pub const RECORD_NOT_FOUND: i32 = 40401;
31    pub const METHOD_NOT_ALLOWED: i32 = 405;
32    pub const CONFLICT: i32 = 409;
33    pub const UNPROCESSABLE_ENTITY: i32 = 422;
34    pub const TOO_MANY_REQUESTS: i32 = 429;
35    pub const INTERNAL: i32 = 500;
36    pub const SERVICE_UNAVAILABLE: i32 = 503;
37}
38
39// ──── 统一响应体 ─────────────────────────────────────
40
41/// 统一 API 响应结构
42#[derive(Debug, Clone, Serialize)]
43pub struct Res<T: Serialize = ()> {
44    /// 业务码,200 表示成功
45    pub code: i32,
46    /// 提示信息
47    pub msg: String,
48    /// 数据载荷
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub data: Option<T>,
51}
52
53/// 分页数据结构
54#[derive(Debug, Clone, Serialize)]
55pub struct PageData<T: Serialize> {
56    /// 数据列表
57    pub list: T,
58    /// 总条数
59    pub total: i64,
60    /// 当前页码
61    pub page: i64,
62    /// 每页条数
63    #[serde(rename = "pageSize")]
64    pub page_size: i64,
65}
66
67/// API 响应结果类型
68pub type ResResult<T> = std::result::Result<Res<T>, ApiError>;
69
70// ──── 分页参数 ──────────────────────────────────────
71
72/// 分页查询参数(公共类型,所有 crate 可用)
73#[derive(Debug, Clone, serde::Deserialize)]
74pub struct PageQuery {
75    /// 页码(从 1 开始)
76    pub page: i64,
77    /// 每页条数
78    pub page_size: i64,
79}
80
81impl PageQuery {
82    /// 创建分页参数,自动规整到合法范围
83    ///
84    /// - `page`: 页码(最小为 1,最大为 1_000_000 防止溢出)
85    /// - `page_size`: 每页条数(范围 [1, 1000])
86    ///
87    /// 超出范围的值会被自动修正到边界。
88    pub fn new(page: i64, page_size: i64) -> Self {
89        let page = page.clamp(1, 1_000_000);
90        let page_size = page_size.clamp(1, 1000);
91        Self { page, page_size }
92    }
93
94    /// 从查询参数创建分页,支持 `Option<u64>` / `Option<i64>` / `Option<i32>` 等整数类型
95    ///
96    /// - `page`: 页码(默认 1)
97    /// - `page_size`: 每页条数(默认 10)
98    pub fn from_query<P: TryInto<i64>, S: TryInto<i64>>(
99        page: Option<P>,
100        page_size: Option<S>,
101    ) -> Self {
102        let page = page
103            .and_then(|v| v.try_into().ok())
104            .unwrap_or(1)
105            .clamp(1, 1_000_000);
106        let page_size = page_size
107            .and_then(|v| v.try_into().ok())
108            .unwrap_or(10)
109            .clamp(1, 1000);
110        Self { page, page_size }
111    }
112
113    /// 计算 SQL OFFSET:`(page - 1) * page_size`(饱和运算防溢出)
114    pub fn offset(&self) -> i64 {
115        (self.page - 1).saturating_mul(self.page_size)
116    }
117    /// 获取 LIMIT 值(即 `page_size`)
118    pub fn limit(&self) -> i64 {
119        self.page_size
120    }
121}
122
123// ──── Res 实现 ──────────────────────────────────────
124
125impl Res<()> {
126    /// 成功(无数据载荷),返回 `{code: 200, msg: <注册表>}`(data 字段因 `skip_serializing_if` 省略)
127    pub fn ok_empty() -> Self {
128        Self {
129            code: codes::OK,
130            msg: error_message_of(ErrorCode::Ok),
131            data: None,
132        }
133    }
134
135    /// 成功(自定义消息,无数据载荷)
136    pub fn ok_msg(msg: impl Into<String>) -> Self {
137        Self {
138            code: codes::OK,
139            msg: msg.into(),
140            data: None,
141        }
142    }
143}
144
145impl<T: Serialize> Res<T> {
146    /// 成功响应,携带数据载荷
147    ///
148    /// # 示例
149    ///
150    /// ```ignore
151    /// Res::ok(user)          // => {code: 200, msg: <注册表>, data: user}
152    /// Res::ok("hello")       // => {code: 200, msg: <注册表>, data: "hello"}
153    /// ```
154    pub fn ok(data: T) -> Self {
155        Self {
156            code: codes::OK,
157            msg: error_message_of(ErrorCode::Ok),
158            data: Some(data),
159        }
160    }
161
162    /// 成功响应,携带数据载荷和自定义消息
163    pub fn ok_with_msg(data: T, msg: impl Into<String>) -> Self {
164        Self {
165            code: codes::OK,
166            msg: msg.into(),
167            data: Some(data),
168        }
169    }
170
171    /// 失败响应(自定义错误码和消息,无数据载荷)
172    ///
173    /// # 示例
174    ///
175    /// ```ignore
176    /// Res::fail(codes::BAD_REQUEST, "用户名不能为空")
177    /// ```
178    pub fn fail(code: i32, msg: impl Into<String>) -> Self {
179        Self {
180            code,
181            msg: msg.into(),
182            data: None,
183        }
184    }
185}
186
187impl<T: Serialize> Res<PageData<T>> {
188    /// 分页响应
189    pub fn page(list: T, total: i64, page: i64, page_size: i64) -> Self {
190        Self::ok(PageData {
191            list,
192            total,
193            page,
194            page_size,
195        })
196    }
197}
198
199// ──── API 错误 ──────────────────────────────────────
200
201/// API 错误(对外暴露的统一错误类型)
202///
203/// HTTP 状态码使用 u16 存储,与 Web 框架解耦。
204#[derive(Debug)]
205pub struct ApiError {
206    /// 业务码
207    pub code: i32,
208    /// 对外消息(已脱敏,不泄露内部信息)
209    pub msg: Cow<'static, str>,
210    /// HTTP 状态码(u16,与 axum::StatusCode 互转)
211    pub status: u16,
212    /// 内部调试信息(仅日志记录,不返回前端)
213    pub internal_detail: Option<String>,
214    /// 源代码位置(仅 debug 模式,自动捕获 file:line,供 IDE 快速跳转)
215    pub source_location: Option<String>,
216}
217
218impl ApiError {
219    /// 创建 API 错误
220    ///
221    /// - `status`: HTTP 状态码(如 400、401、500)
222    /// - `code`: 业务错误码
223    /// - `msg`: 对外提示消息
224    pub fn new(status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Self {
225        Self {
226            status,
227            code,
228            msg: msg.into(),
229            internal_detail: None,
230            source_location: None,
231        }
232    }
233
234    /// 附加内部调试详情(仅写入日志,不暴露给前端)
235    fn with_detail(mut self, detail: impl Into<String>) -> Self {
236        self.internal_detail = Some(detail.into());
237        self
238    }
239
240    /// 工厂方法公共构造:捕获调用位置并记录业务错误日志(debug 模式)
241    ///
242    /// 所有工厂方法经此构造,source_location 捕获与日志逻辑只需维护一份。
243    #[track_caller]
244    fn tracked(status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Self {
245        let mut err = Self::new(status, code, msg);
246        #[cfg(debug_assertions)]
247        {
248            let caller = std::panic::Location::caller();
249            let loc = format!("{}:{}", caller.file(), caller.line());
250            err.source_location = Some(loc.clone());
251            tracing::info!(target: "wordval_biz_error", location = %loc, code = err.code, msg = %err.msg, "业务错误");
252        }
253        err
254    }
255
256    // ── 工厂方法 ──
257
258    /// 400 Bad Request:客户端请求格式或参数错误
259    #[track_caller]
260    pub fn bad_request(msg: impl Into<Cow<'static, str>>) -> Self {
261        Self::tracked(400, codes::BAD_REQUEST, msg)
262    }
263
264    /// 401 Unauthorized:未认证或 Token 无效
265    #[track_caller]
266    pub fn unauthorized(msg: impl Into<Cow<'static, str>>) -> Self {
267        Self::tracked(401, codes::UNAUTHORIZED, msg)
268    }
269
270    /// 403 Forbidden:已认证但权限不足
271    #[track_caller]
272    pub fn forbidden(msg: impl Into<Cow<'static, str>>) -> Self {
273        Self::tracked(403, codes::FORBIDDEN, msg)
274    }
275
276    /// 404 Not Found:资源不存在(寻址级)
277    ///
278    /// 路由未命中、路径参数缺失、静态资源不存在等「请求地址没有对应资源」的
279    /// 情形,业务码 [`codes::NOT_FOUND`](404)。数据库记录级的"记录不存在"
280    /// 请用 [`Self::record_not_found`](业务码 40401),前端可按 `code` 区分。
281    #[track_caller]
282    pub fn not_found(msg: impl Into<Cow<'static, str>>) -> Self {
283        Self::tracked(404, codes::NOT_FOUND, msg)
284    }
285
286    /// 404 Not Found:目标记录不存在(数据级)
287    ///
288    /// HTTP 状态仍为 404(寻址的资源没有表示),业务码为 [`codes::RECORD_NOT_FOUND`](40401),
289    /// 前端可与路由 404 区分:`code == 404` → 地址错了;`code == 40401` → 地址对但记录没了。
290    /// 对应 `DbError::NotFound`(`Q::one`/`Q::one_as` 空结果)的自动映射。
291    #[track_caller]
292    pub fn record_not_found(msg: impl Into<Cow<'static, str>>) -> Self {
293        Self::tracked(404, codes::RECORD_NOT_FOUND, msg)
294    }
295
296    /// 405 Method Not Allowed:HTTP 方法不正确
297    #[track_caller]
298    pub fn method_not_allowed(msg: impl Into<Cow<'static, str>>) -> Self {
299        Self::tracked(405, codes::METHOD_NOT_ALLOWED, msg)
300    }
301
302    /// 409 Conflict:资源冲突(如重复创建)
303    #[track_caller]
304    pub fn conflict(msg: impl Into<Cow<'static, str>>) -> Self {
305        Self::tracked(409, codes::CONFLICT, msg)
306    }
307
308    /// 422 Unprocessable Entity:请求体语义错误(如字段校验失败)
309    #[track_caller]
310    pub fn unprocessable_entity(msg: impl Into<Cow<'static, str>>) -> Self {
311        Self::tracked(422, codes::UNPROCESSABLE_ENTITY, msg)
312    }
313
314    /// 429 Too Many Requests:请求频率超限
315    #[track_caller]
316    pub fn too_many_requests(msg: impl Into<Cow<'static, str>>) -> Self {
317        Self::tracked(429, codes::TOO_MANY_REQUESTS, msg)
318    }
319
320    /// 500 Internal Server Error:服务端内部错误
321    ///
322    /// 前端仅看到模糊提示;完整错误需通过日志排查。
323    #[track_caller]
324    pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
325        Self::tracked(500, codes::INTERNAL, msg)
326    }
327
328    /// 500 Internal Server Error(带调试详情)
329    ///
330    /// - `public_msg`: 返回前端的模糊提示
331    /// - `detail`: 内部日志记录的详细信息(如完整的错误栈)
332    #[track_caller]
333    pub fn internal_masked(
334        public_msg: impl Into<Cow<'static, str>>,
335        detail: impl Into<String>,
336    ) -> Self {
337        Self::tracked(500, codes::INTERNAL, public_msg).with_detail(detail)
338    }
339
340    /// 503 Service Unavailable:服务暂时不可用
341    #[track_caller]
342    pub fn service_unavailable(msg: impl Into<Cow<'static, str>>) -> Self {
343        Self::tracked(503, codes::SERVICE_UNAVAILABLE, msg)
344    }
345
346    // ── ErrorCode 工厂方法 ──
347
348    /// 使用 [`ErrorCode`] 创建错误(提示文本从注册表查找,用户可覆盖)
349    ///
350    /// # 示例
351    ///
352    /// ```ignore
353    /// use wordval_core::ErrorCode;
354    ///
355    /// Err(ApiError::from_code(ErrorCode::Unauthorized))
356    /// ```
357    #[track_caller]
358    pub fn from_code(code: ErrorCode) -> Self {
359        Self::tracked(code.http_status(), code as i32, error_message_of(code))
360    }
361
362    /// 使用 [`ErrorCode`] + 内部调试详情
363    ///
364    /// 前端看到注册表中的提示文本,日志记录 `detail` 用于排查。
365    ///
366    /// # 示例
367    ///
368    /// ```ignore
369    /// Err(ApiError::from_code_detail(ErrorCode::Internal, format!("db error: {}", e)))
370    /// ```
371    #[track_caller]
372    pub fn from_code_detail(code: ErrorCode, detail: impl Into<String>) -> Self {
373        Self::tracked(code.http_status(), code as i32, error_message_of(code)).with_detail(detail)
374    }
375}
376
377impl From<Error> for ApiError {
378    #[track_caller]
379    fn from(e: Error) -> Self {
380        // ApiError → Error → ApiError 往返必须无损:401/404 等状态码
381        // 在 Result<T, Error> 传播中不能被压成 500
382        match e {
383            Error::Api(e) => e,
384            e => {
385                tracing::error!(target: "wordval_error", detail = %e, "内部错误");
386                ApiError::internal_masked(error_message_of(ErrorCode::Internal), e.to_string())
387            }
388        }
389    }
390}
391
392impl std::fmt::Display for ApiError {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        write!(f, "[{}] {}", self.code, self.msg)
395    }
396}
397
398impl std::error::Error for ApiError {}
399
400#[cfg(feature = "db")]
401impl From<sqlx::Error> for ApiError {
402    #[track_caller]
403    fn from(e: sqlx::Error) -> Self {
404        let detail = e.to_string();
405        // 日志打印 detail 用于排查,前端只看到注册表中的模糊提示
406        tracing::error!(target: "wordval_sqlx_error", detail = %detail, "SQL 查询异常");
407        ApiError::internal_masked(error_message_of(ErrorCode::Internal), detail)
408    }
409}
410
411/// 错误位置追踪宏 —— 自动捕获 file!() / line!() / column!() 写入 ApiError
412///
413/// **debug 模式**: 记录 full location + error 到 tracing,写入 internal_detail
414/// **release 模式**: 仅透传错误信息,无 file/line 字符串,零额外开销
415///
416/// # 用法
417///
418/// ```ignore
419/// db().query(...).await.map_err(|e| trace_error!(e))?;
420/// db().query(...).await.map_err(|e| trace_error!(e, "查询失败"))?;
421/// ```
422#[cfg(debug_assertions)]
423#[macro_export]
424macro_rules! trace_error {
425    ($error:expr) => {{
426        let detail = format!("{} at {}:{}:{}", $error, file!(), line!(), column!());
427        tracing::error!(target: "wordval_error", error = %$error, file = file!(), line = line!(), "❌ ierr");
428        $crate::api::ApiError::internal_masked($crate::error_registry::error_message_of($crate::error_registry::ErrorCode::Internal), detail)
429    }};
430    ($error:expr, $context:expr) => {{
431        let detail = format!("{} ({}) at {}:{}:{}", $error, $context, file!(), line!(), column!());
432        tracing::error!(target: "wordval_error", error = %$error, context = $context, file = file!(), line = line!(), "❌ ierr");
433        $crate::api::ApiError::internal_masked($context, detail)
434    }};
435}
436
437#[cfg(not(debug_assertions))]
438#[macro_export]
439macro_rules! trace_error {
440    ($error:expr) => {{
441        // release 同样必须脱敏:原文只进日志(internal_detail),不进响应 msg
442        tracing::error!(target: "wordval_error", error = %$error, "❌ ierr");
443        $crate::api::ApiError::internal_masked(
444            $crate::error_registry::error_message_of($crate::error_registry::ErrorCode::Internal),
445            format!("{}", $error),
446        )
447    }};
448    ($error:expr, $context:expr) => {{
449        tracing::error!(target: "wordval_error", error = %$error, context = $context, "❌ ierr");
450        $crate::api::ApiError::internal_masked($context, format!("{}", $error))
451    }};
452}
453
454// ──── IntoResponse 实现(需 web feature) ───────────
455
456#[cfg(feature = "axum")]
457impl<T: Serialize> IntoResponse for Res<T> {
458    fn into_response(self) -> axum::response::Response {
459        let mut resp = Json(self).into_response();
460        resp.headers_mut().insert(
461            axum::http::HeaderName::from_static("content-type"),
462            axum::http::HeaderValue::from_static("application/json; charset=utf-8"),
463        );
464        resp
465    }
466}
467
468#[cfg(feature = "axum")]
469impl IntoResponse for ApiError {
470    fn into_response(self) -> axum::response::Response {
471        if let Some(ref detail) = self.internal_detail {
472            let status =
473                StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
474            tracing::error!(status = status.as_u16(), code = self.code, detail = %detail,
475                "请求处理异常");
476        }
477        let body = Res::<()>::fail(self.code, self.msg);
478        let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
479        let mut resp = (status, Json(body)).into_response();
480        resp.headers_mut().insert(
481            axum::http::HeaderName::from_static("content-type"),
482            axum::http::HeaderValue::from_static("application/json; charset=utf-8"),
483        );
484        resp
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use crate::error_registry::ErrorCode;
492
493    // ── From<Error> 无损往返 ──
494
495    #[test]
496    fn error_api_roundtrip_preserves_status_and_code() {
497        // 回归:Error::Api 下转 ApiError 不得被压成 500
498        let wrapped = Error::from(ApiError::new(
499            404,
500            codes::NOT_FOUND,
501            error_message_of(ErrorCode::NotFound),
502        ));
503        let back = ApiError::from(wrapped);
504        assert_eq!(back.status, 404, "Error::Api 往返必须保留 status");
505        assert_eq!(back.code, codes::NOT_FOUND, "往返必须保留业务码");
506        // 非 Api 变体仍压成 500(含脱敏 msg)
507        let internal = ApiError::from(Error::Msg("数据库连接失败细节".into()));
508        assert_eq!(internal.status, 500);
509        assert_ne!(internal.msg, "数据库连接失败细节");
510    }
511
512    // ── Res 构造与序列化 ──
513
514    #[test]
515    fn res_ok_serialization() {
516        let res = Res::ok(42);
517        let json = serde_json::to_value(&res).unwrap();
518        assert_eq!(json["code"], 200);
519        assert_eq!(json["data"], 42);
520        assert_eq!(json["msg"], error_message_of(ErrorCode::Ok));
521    }
522
523    #[test]
524    fn res_ok_empty_omits_data() {
525        let res = Res::ok_empty();
526        let json = serde_json::to_value(&res).unwrap();
527        assert_eq!(json["code"], 200);
528        assert!(json.get("data").is_none(), "data 应被 skip_serializing_if 省略");
529    }
530
531    #[test]
532    fn res_ok_msg_and_ok_with_msg() {
533        let a = Res::ok_msg("自定义");
534        assert_eq!(a.code, codes::OK);
535        assert_eq!(a.msg, "自定义");
536        assert!(a.data.is_none());
537
538        let b = Res::ok_with_msg("hi", "带数据");
539        assert_eq!(b.msg, "带数据");
540        assert_eq!(b.data, Some("hi"));
541    }
542
543    #[test]
544    fn res_fail_carries_code_msg_no_data() {
545        let res: Res<()> = Res::fail(codes::BAD_REQUEST, "用户名不能为空");
546        let json = serde_json::to_value(&res).unwrap();
547        assert_eq!(json["code"], 400);
548        assert_eq!(json["msg"], "用户名不能为空");
549        assert!(json.get("data").is_none());
550    }
551
552    #[test]
553    fn res_page_builds_page_data() {
554        let res = Res::page(vec![1, 2, 3], 100, 2, 3);
555        let json = serde_json::to_value(&res).unwrap();
556        assert_eq!(json["data"]["total"], 100);
557        assert_eq!(json["data"]["page"], 2);
558        assert_eq!(json["data"]["pageSize"], 3);
559        assert_eq!(json["data"]["list"], serde_json::json!([1, 2, 3]));
560    }
561
562    // ── PageQuery ──
563
564    #[test]
565    fn page_query_clamps_bounds() {
566        let q = PageQuery::new(0, 0);
567        assert_eq!((q.page, q.page_size), (1, 1));
568        let q = PageQuery::new(i64::MAX, i64::MAX);
569        assert_eq!((q.page, q.page_size), (1_000_000, 1000));
570        let q = PageQuery::new(-5, -10);
571        assert_eq!((q.page, q.page_size), (1, 1));
572    }
573
574    #[test]
575    fn page_query_from_query_defaults_and_types() {
576        let q = PageQuery::from_query(None::<u64>, None::<u64>);
577        assert_eq!((q.page, q.page_size), (1, 10));
578        let q = PageQuery::from_query(Some(3u64), Some(50i64));
579        assert_eq!((q.page, q.page_size), (3, 50));
580        let q = PageQuery::from_query(Some(9_999_999u32), Some(0i32));
581        assert_eq!((q.page, q.page_size), (1_000_000, 1));
582    }
583
584    #[test]
585    fn page_query_offset_limit() {
586        let q = PageQuery::new(3, 20);
587        assert_eq!(q.offset(), 40);
588        assert_eq!(q.limit(), 20);
589        // 饱和乘法不溢出
590        let q = PageQuery::new(1_000_000, 1000);
591        assert_eq!(q.offset(), 999_999_000);
592    }
593
594    // ── ApiError 工厂方法 ──
595
596    #[test]
597    fn api_error_factories_status_and_code() {
598        let cases: Vec<(ApiError, u16, i32)> = vec![
599            (ApiError::bad_request("a"), 400, codes::BAD_REQUEST),
600            (ApiError::unauthorized("a"), 401, codes::UNAUTHORIZED),
601            (ApiError::forbidden("a"), 403, codes::FORBIDDEN),
602            (ApiError::not_found("a"), 404, codes::NOT_FOUND),
603            (ApiError::record_not_found("a"), 404, codes::RECORD_NOT_FOUND),
604            (ApiError::method_not_allowed("a"), 405, codes::METHOD_NOT_ALLOWED),
605            (ApiError::conflict("a"), 409, codes::CONFLICT),
606            (ApiError::unprocessable_entity("a"), 422, codes::UNPROCESSABLE_ENTITY),
607            (ApiError::too_many_requests("a"), 429, codes::TOO_MANY_REQUESTS),
608            (ApiError::internal("a"), 500, codes::INTERNAL),
609            (ApiError::service_unavailable("a"), 503, codes::SERVICE_UNAVAILABLE),
610        ];
611        for (e, status, code) in cases {
612            assert_eq!(e.status, status);
613            assert_eq!(e.code, code);
614            assert_eq!(e.msg, "a");
615        }
616        // 两级 404:HTTP 状态相同,业务码必须可区分(路由 404 vs 记录 40401)
617        assert_ne!(
618            ApiError::not_found("a").code,
619            ApiError::record_not_found("a").code,
620            "路由级与记录级 404 必须可通过业务码区分"
621        );
622    }
623
624    #[test]
625    fn api_error_internal_masked_keeps_detail() {
626        let e = ApiError::internal_masked("对外提示", "秘密内部栈");
627        assert_eq!(e.status, 500);
628        assert_eq!(e.msg, "对外提示");
629        assert_eq!(e.internal_detail.as_deref(), Some("秘密内部栈"));
630    }
631
632    #[test]
633    fn api_error_from_code_uses_registry() {
634        let e = ApiError::from_code(ErrorCode::NotFound);
635        assert_eq!(e.status, 404);
636        assert_eq!(e.code, 404);
637        assert_eq!(e.msg, error_message_of(ErrorCode::NotFound));
638
639        let e = ApiError::from_code_detail(ErrorCode::Internal, "db down");
640        assert_eq!(e.code, 500);
641        assert_eq!(e.internal_detail.as_deref(), Some("db down"));
642    }
643
644    #[test]
645    fn api_error_from_core_error_is_masked_500() {
646        let e: ApiError = Error::Config("bad toml".into()).into();
647        assert_eq!(e.status, 500);
648        assert_eq!(e.code, codes::INTERNAL);
649        // 对外消息来自注册表,不泄露内部细节
650        assert_eq!(e.msg, error_message_of(ErrorCode::Internal));
651        assert!(e.internal_detail.unwrap().contains("bad toml"));
652    }
653
654    #[test]
655    fn api_error_display_and_std_error() {
656        let e = ApiError::not_found("用户不存在");
657        assert_eq!(e.to_string(), "[404] 用户不存在");
658        let boxed: Box<dyn std::error::Error> = Box::new(e);
659        assert!(boxed.to_string().contains("404"));
660    }
661
662    #[test]
663    fn api_error_new_without_tracking() {
664        let e = ApiError::new(418, -1, "teapot");
665        assert_eq!((e.status, e.code), (418, -1));
666        assert!(e.internal_detail.is_none());
667    }
668
669    #[test]
670    fn trace_error_macro_produces_internal() {
671        let io = std::io::Error::other("disk full");
672        let e = trace_error!(io);
673        assert_eq!(e.code, codes::INTERNAL);
674        let e = trace_error!("plain", "上下文");
675        assert_eq!(e.code, codes::INTERNAL);
676    }
677
678    // ── IntoResponse(需 web feature) ──
679
680    #[cfg(feature = "axum")]
681    mod web_responses {
682        use super::*;
683        use axum::body::to_bytes;
684        use axum::http::StatusCode;
685
686        #[tokio::test]
687        async fn res_into_response_json_with_charset() {
688            let resp = Res::ok("hi").into_response();
689            assert_eq!(resp.status(), StatusCode::OK);
690            assert_eq!(
691                resp.headers()["content-type"],
692                "application/json; charset=utf-8"
693            );
694            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
695            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
696            assert_eq!(json["code"], 200);
697            assert_eq!(json["data"], "hi");
698        }
699
700        #[tokio::test]
701        async fn api_error_into_response_keeps_status_and_hides_detail() {
702            let resp = ApiError::not_found("没找到").into_response();
703            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
704            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
705            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
706            assert_eq!(json["code"], 404);
707            assert_eq!(json["msg"], "没找到");
708            assert!(json.get("data").is_none());
709        }
710
711        #[tokio::test]
712        async fn api_error_invalid_status_falls_back_to_500() {
713            // 非法 HTTP 状态码(超出 100..=999)回退为 500,业务码保留
714            let resp = ApiError::new(1000, 12345, "x").into_response();
715            assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
716            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
717            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
718            assert_eq!(json["code"], 12345);
719        }
720    }
721}