wordval-core 1.0.8

Wordval framework core: app lifecycle, plugin system, error handling, unified response types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! 框架核心 API 类型:响应体、错误、分页数据、错误码
//!
//! 这些类型是框架的公共"语言",所有 crate 都依赖它们。
//! `IntoResponse` 实现通过 `features = ["web"]` 开启。

use crate::error_registry::{error_message_of, ErrorCode};
use crate::Error;
use serde::Serialize;
use std::borrow::Cow;

#[cfg(feature = "axum")]
use axum::{
    http::StatusCode,
    response::{IntoResponse, Json},
};

// ──── 错误码常量 ────────────────────────────────────

/// 业务码体系:`code == HTTP status` 为通用 HTTP 语义;`code = status*100 + 序号`
/// (如 `RECORD_NOT_FOUND` = 40401)为业务细分子码——HTTP 层语义不变,前端可按
/// `code` 精确区分同一 HTTP 状态下的不同业务情形。
pub mod codes {
    pub const OK: i32 = 200;
    pub const BAD_REQUEST: i32 = 400;
    pub const UNAUTHORIZED: i32 = 401;
    pub const FORBIDDEN: i32 = 403;
    pub const NOT_FOUND: i32 = 404;
    /// 记录不存在(数据级 404 子码):`Q::one`/`Q::one_as` 空结果等
    /// 「目标记录理应存在却缺失」的情形,区别于路由/寻址级的 [`NOT_FOUND`]。
    pub const RECORD_NOT_FOUND: i32 = 40401;
    pub const METHOD_NOT_ALLOWED: i32 = 405;
    pub const CONFLICT: i32 = 409;
    pub const UNPROCESSABLE_ENTITY: i32 = 422;
    pub const TOO_MANY_REQUESTS: i32 = 429;
    pub const INTERNAL: i32 = 500;
    pub const SERVICE_UNAVAILABLE: i32 = 503;
}

// ──── 统一响应体 ─────────────────────────────────────

/// 统一 API 响应结构
#[derive(Debug, Clone, Serialize)]
pub struct Res<T: Serialize = ()> {
    /// 业务码,200 表示成功
    pub code: i32,
    /// 提示信息
    pub msg: String,
    /// 数据载荷
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<T>,
}

/// 分页数据结构
#[derive(Debug, Clone, Serialize)]
pub struct PageData<T: Serialize> {
    /// 数据列表
    pub list: T,
    /// 总条数
    pub total: i64,
    /// 当前页码
    pub page: i64,
    /// 每页条数
    #[serde(rename = "pageSize")]
    pub page_size: i64,
}

/// API 响应结果类型
pub type ResResult<T> = std::result::Result<Res<T>, ApiError>;

// ──── 分页参数 ──────────────────────────────────────

/// 分页查询参数(公共类型,所有 crate 可用)
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PageQuery {
    /// 页码(从 1 开始)
    pub page: i64,
    /// 每页条数
    pub page_size: i64,
}

impl PageQuery {
    /// 创建分页参数,自动规整到合法范围
    ///
    /// - `page`: 页码(最小为 1,最大为 1_000_000 防止溢出)
    /// - `page_size`: 每页条数(范围 [1, 1000])
    ///
    /// 超出范围的值会被自动修正到边界。
    pub fn new(page: i64, page_size: i64) -> Self {
        let page = page.clamp(1, 1_000_000);
        let page_size = page_size.clamp(1, 1000);
        Self { page, page_size }
    }

    /// 从查询参数创建分页,支持 `Option<u64>` / `Option<i64>` / `Option<i32>` 等整数类型
    ///
    /// - `page`: 页码(默认 1)
    /// - `page_size`: 每页条数(默认 10)
    pub fn from_query<P: TryInto<i64>, S: TryInto<i64>>(
        page: Option<P>,
        page_size: Option<S>,
    ) -> Self {
        let page = page
            .and_then(|v| v.try_into().ok())
            .unwrap_or(1)
            .clamp(1, 1_000_000);
        let page_size = page_size
            .and_then(|v| v.try_into().ok())
            .unwrap_or(10)
            .clamp(1, 1000);
        Self { page, page_size }
    }

    /// 计算 SQL OFFSET:`(page - 1) * page_size`(饱和运算防溢出)
    pub fn offset(&self) -> i64 {
        (self.page - 1).saturating_mul(self.page_size)
    }
    /// 获取 LIMIT 值(即 `page_size`)
    pub fn limit(&self) -> i64 {
        self.page_size
    }
}

// ──── Res 实现 ──────────────────────────────────────

impl Res<()> {
    /// 成功(无数据载荷),返回 `{code: 200, msg: <注册表>}`(data 字段因 `skip_serializing_if` 省略)
    pub fn ok_empty() -> Self {
        Self {
            code: codes::OK,
            msg: error_message_of(ErrorCode::Ok),
            data: None,
        }
    }

    /// 成功(自定义消息,无数据载荷)
    pub fn ok_msg(msg: impl Into<String>) -> Self {
        Self {
            code: codes::OK,
            msg: msg.into(),
            data: None,
        }
    }
}

impl<T: Serialize> Res<T> {
    /// 成功响应,携带数据载荷
    ///
    /// # 示例
    ///
    /// ```ignore
    /// Res::ok(user)          // => {code: 200, msg: <注册表>, data: user}
    /// Res::ok("hello")       // => {code: 200, msg: <注册表>, data: "hello"}
    /// ```
    pub fn ok(data: T) -> Self {
        Self {
            code: codes::OK,
            msg: error_message_of(ErrorCode::Ok),
            data: Some(data),
        }
    }

    /// 成功响应,携带数据载荷和自定义消息
    pub fn ok_with_msg(data: T, msg: impl Into<String>) -> Self {
        Self {
            code: codes::OK,
            msg: msg.into(),
            data: Some(data),
        }
    }

    /// 失败响应(自定义错误码和消息,无数据载荷)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// Res::fail(codes::BAD_REQUEST, "用户名不能为空")
    /// ```
    pub fn fail(code: i32, msg: impl Into<String>) -> Self {
        Self {
            code,
            msg: msg.into(),
            data: None,
        }
    }
}

impl<T: Serialize> Res<PageData<T>> {
    /// 分页响应
    pub fn page(list: T, total: i64, page: i64, page_size: i64) -> Self {
        Self::ok(PageData {
            list,
            total,
            page,
            page_size,
        })
    }
}

// ──── API 错误 ──────────────────────────────────────

/// API 错误(对外暴露的统一错误类型)
///
/// HTTP 状态码使用 u16 存储,与 Web 框架解耦。
#[derive(Debug)]
pub struct ApiError {
    /// 业务码
    pub code: i32,
    /// 对外消息(已脱敏,不泄露内部信息)
    pub msg: Cow<'static, str>,
    /// HTTP 状态码(u16,与 axum::StatusCode 互转)
    pub status: u16,
    /// 内部调试信息(仅日志记录,不返回前端)
    pub internal_detail: Option<String>,
    /// 源代码位置(仅 debug 模式,自动捕获 file:line,供 IDE 快速跳转)
    pub source_location: Option<String>,
}

impl ApiError {
    /// 创建 API 错误
    ///
    /// - `status`: HTTP 状态码(如 400、401、500)
    /// - `code`: 业务错误码
    /// - `msg`: 对外提示消息
    pub fn new(status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Self {
        Self {
            status,
            code,
            msg: msg.into(),
            internal_detail: None,
            source_location: None,
        }
    }

    /// 附加内部调试详情(仅写入日志,不暴露给前端)
    fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.internal_detail = Some(detail.into());
        self
    }

    /// 工厂方法公共构造:捕获调用位置并记录业务错误日志(debug 模式)
    ///
    /// 所有工厂方法经此构造,source_location 捕获与日志逻辑只需维护一份。
    #[track_caller]
    fn tracked(status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Self {
        let mut err = Self::new(status, code, msg);
        #[cfg(debug_assertions)]
        {
            let caller = std::panic::Location::caller();
            let loc = format!("{}:{}", caller.file(), caller.line());
            err.source_location = Some(loc.clone());
            tracing::info!(target: "wordval_biz_error", location = %loc, code = err.code, msg = %err.msg, "业务错误");
        }
        err
    }

    // ── 工厂方法 ──

    /// 400 Bad Request:客户端请求格式或参数错误
    #[track_caller]
    pub fn bad_request(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(400, codes::BAD_REQUEST, msg)
    }

    /// 401 Unauthorized:未认证或 Token 无效
    #[track_caller]
    pub fn unauthorized(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(401, codes::UNAUTHORIZED, msg)
    }

    /// 403 Forbidden:已认证但权限不足
    #[track_caller]
    pub fn forbidden(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(403, codes::FORBIDDEN, msg)
    }

    /// 404 Not Found:资源不存在(寻址级)
    ///
    /// 路由未命中、路径参数缺失、静态资源不存在等「请求地址没有对应资源」的
    /// 情形,业务码 [`codes::NOT_FOUND`](404)。数据库记录级的"记录不存在"
    /// 请用 [`Self::record_not_found`](业务码 40401),前端可按 `code` 区分。
    #[track_caller]
    pub fn not_found(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(404, codes::NOT_FOUND, msg)
    }

    /// 404 Not Found:目标记录不存在(数据级)
    ///
    /// HTTP 状态仍为 404(寻址的资源没有表示),业务码为 [`codes::RECORD_NOT_FOUND`](40401),
    /// 前端可与路由 404 区分:`code == 404` → 地址错了;`code == 40401` → 地址对但记录没了。
    /// 对应 `DbError::NotFound`(`Q::one`/`Q::one_as` 空结果)的自动映射。
    #[track_caller]
    pub fn record_not_found(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(404, codes::RECORD_NOT_FOUND, msg)
    }

    /// 405 Method Not Allowed:HTTP 方法不正确
    #[track_caller]
    pub fn method_not_allowed(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(405, codes::METHOD_NOT_ALLOWED, msg)
    }

    /// 409 Conflict:资源冲突(如重复创建)
    #[track_caller]
    pub fn conflict(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(409, codes::CONFLICT, msg)
    }

    /// 422 Unprocessable Entity:请求体语义错误(如字段校验失败)
    #[track_caller]
    pub fn unprocessable_entity(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(422, codes::UNPROCESSABLE_ENTITY, msg)
    }

    /// 429 Too Many Requests:请求频率超限
    #[track_caller]
    pub fn too_many_requests(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(429, codes::TOO_MANY_REQUESTS, msg)
    }

    /// 500 Internal Server Error:服务端内部错误
    ///
    /// 前端仅看到模糊提示;完整错误需通过日志排查。
    #[track_caller]
    pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(500, codes::INTERNAL, msg)
    }

    /// 500 Internal Server Error(带调试详情)
    ///
    /// - `public_msg`: 返回前端的模糊提示
    /// - `detail`: 内部日志记录的详细信息(如完整的错误栈)
    #[track_caller]
    pub fn internal_masked(
        public_msg: impl Into<Cow<'static, str>>,
        detail: impl Into<String>,
    ) -> Self {
        Self::tracked(500, codes::INTERNAL, public_msg).with_detail(detail)
    }

    /// 503 Service Unavailable:服务暂时不可用
    #[track_caller]
    pub fn service_unavailable(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::tracked(503, codes::SERVICE_UNAVAILABLE, msg)
    }

    // ── ErrorCode 工厂方法 ──

    /// 使用 [`ErrorCode`] 创建错误(提示文本从注册表查找,用户可覆盖)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// use wordval_core::ErrorCode;
    ///
    /// Err(ApiError::from_code(ErrorCode::Unauthorized))
    /// ```
    #[track_caller]
    pub fn from_code(code: ErrorCode) -> Self {
        Self::tracked(code.http_status(), code as i32, error_message_of(code))
    }

    /// 使用 [`ErrorCode`] + 内部调试详情
    ///
    /// 前端看到注册表中的提示文本,日志记录 `detail` 用于排查。
    ///
    /// # 示例
    ///
    /// ```ignore
    /// Err(ApiError::from_code_detail(ErrorCode::Internal, format!("db error: {}", e)))
    /// ```
    #[track_caller]
    pub fn from_code_detail(code: ErrorCode, detail: impl Into<String>) -> Self {
        Self::tracked(code.http_status(), code as i32, error_message_of(code)).with_detail(detail)
    }
}

impl From<Error> for ApiError {
    #[track_caller]
    fn from(e: Error) -> Self {
        // ApiError → Error → ApiError 往返必须无损:401/404 等状态码
        // 在 Result<T, Error> 传播中不能被压成 500
        match e {
            Error::Api(e) => e,
            e => {
                tracing::error!(target: "wordval_error", detail = %e, "内部错误");
                ApiError::internal_masked(error_message_of(ErrorCode::Internal), e.to_string())
            }
        }
    }
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.code, self.msg)
    }
}

impl std::error::Error for ApiError {}

#[cfg(feature = "db")]
impl From<sqlx::Error> for ApiError {
    #[track_caller]
    fn from(e: sqlx::Error) -> Self {
        let detail = e.to_string();
        // 日志打印 detail 用于排查,前端只看到注册表中的模糊提示
        tracing::error!(target: "wordval_sqlx_error", detail = %detail, "SQL 查询异常");
        ApiError::internal_masked(error_message_of(ErrorCode::Internal), detail)
    }
}

/// 错误位置追踪宏 —— 自动捕获 file!() / line!() / column!() 写入 ApiError
///
/// **debug 模式**: 记录 full location + error 到 tracing,写入 internal_detail
/// **release 模式**: 仅透传错误信息,无 file/line 字符串,零额外开销
///
/// # 用法
///
/// ```ignore
/// db().query(...).await.map_err(|e| trace_error!(e))?;
/// db().query(...).await.map_err(|e| trace_error!(e, "查询失败"))?;
/// ```
#[cfg(debug_assertions)]
#[macro_export]
macro_rules! trace_error {
    ($error:expr) => {{
        let detail = format!("{} at {}:{}:{}", $error, file!(), line!(), column!());
        tracing::error!(target: "wordval_error", error = %$error, file = file!(), line = line!(), "❌ ierr");
        $crate::api::ApiError::internal_masked($crate::error_registry::error_message_of($crate::error_registry::ErrorCode::Internal), detail)
    }};
    ($error:expr, $context:expr) => {{
        let detail = format!("{} ({}) at {}:{}:{}", $error, $context, file!(), line!(), column!());
        tracing::error!(target: "wordval_error", error = %$error, context = $context, file = file!(), line = line!(), "❌ ierr");
        $crate::api::ApiError::internal_masked($context, detail)
    }};
}

#[cfg(not(debug_assertions))]
#[macro_export]
macro_rules! trace_error {
    ($error:expr) => {{
        // release 同样必须脱敏:原文只进日志(internal_detail),不进响应 msg
        tracing::error!(target: "wordval_error", error = %$error, "❌ ierr");
        $crate::api::ApiError::internal_masked(
            $crate::error_registry::error_message_of($crate::error_registry::ErrorCode::Internal),
            format!("{}", $error),
        )
    }};
    ($error:expr, $context:expr) => {{
        tracing::error!(target: "wordval_error", error = %$error, context = $context, "❌ ierr");
        $crate::api::ApiError::internal_masked($context, format!("{}", $error))
    }};
}

// ──── IntoResponse 实现(需 web feature) ───────────

#[cfg(feature = "axum")]
impl<T: Serialize> IntoResponse for Res<T> {
    fn into_response(self) -> axum::response::Response {
        let mut resp = Json(self).into_response();
        resp.headers_mut().insert(
            axum::http::HeaderName::from_static("content-type"),
            axum::http::HeaderValue::from_static("application/json; charset=utf-8"),
        );
        resp
    }
}

#[cfg(feature = "axum")]
impl IntoResponse for ApiError {
    fn into_response(self) -> axum::response::Response {
        if let Some(ref detail) = self.internal_detail {
            let status =
                StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            tracing::error!(status = status.as_u16(), code = self.code, detail = %detail,
                "请求处理异常");
        }
        let body = Res::<()>::fail(self.code, self.msg);
        let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        let mut resp = (status, Json(body)).into_response();
        resp.headers_mut().insert(
            axum::http::HeaderName::from_static("content-type"),
            axum::http::HeaderValue::from_static("application/json; charset=utf-8"),
        );
        resp
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error_registry::ErrorCode;

    // ── From<Error> 无损往返 ──

    #[test]
    fn error_api_roundtrip_preserves_status_and_code() {
        // 回归:Error::Api 下转 ApiError 不得被压成 500
        let wrapped = Error::from(ApiError::new(
            404,
            codes::NOT_FOUND,
            error_message_of(ErrorCode::NotFound),
        ));
        let back = ApiError::from(wrapped);
        assert_eq!(back.status, 404, "Error::Api 往返必须保留 status");
        assert_eq!(back.code, codes::NOT_FOUND, "往返必须保留业务码");
        // 非 Api 变体仍压成 500(含脱敏 msg)
        let internal = ApiError::from(Error::Msg("数据库连接失败细节".into()));
        assert_eq!(internal.status, 500);
        assert_ne!(internal.msg, "数据库连接失败细节");
    }

    // ── Res 构造与序列化 ──

    #[test]
    fn res_ok_serialization() {
        let res = Res::ok(42);
        let json = serde_json::to_value(&res).unwrap();
        assert_eq!(json["code"], 200);
        assert_eq!(json["data"], 42);
        assert_eq!(json["msg"], error_message_of(ErrorCode::Ok));
    }

    #[test]
    fn res_ok_empty_omits_data() {
        let res = Res::ok_empty();
        let json = serde_json::to_value(&res).unwrap();
        assert_eq!(json["code"], 200);
        assert!(json.get("data").is_none(), "data 应被 skip_serializing_if 省略");
    }

    #[test]
    fn res_ok_msg_and_ok_with_msg() {
        let a = Res::ok_msg("自定义");
        assert_eq!(a.code, codes::OK);
        assert_eq!(a.msg, "自定义");
        assert!(a.data.is_none());

        let b = Res::ok_with_msg("hi", "带数据");
        assert_eq!(b.msg, "带数据");
        assert_eq!(b.data, Some("hi"));
    }

    #[test]
    fn res_fail_carries_code_msg_no_data() {
        let res: Res<()> = Res::fail(codes::BAD_REQUEST, "用户名不能为空");
        let json = serde_json::to_value(&res).unwrap();
        assert_eq!(json["code"], 400);
        assert_eq!(json["msg"], "用户名不能为空");
        assert!(json.get("data").is_none());
    }

    #[test]
    fn res_page_builds_page_data() {
        let res = Res::page(vec![1, 2, 3], 100, 2, 3);
        let json = serde_json::to_value(&res).unwrap();
        assert_eq!(json["data"]["total"], 100);
        assert_eq!(json["data"]["page"], 2);
        assert_eq!(json["data"]["pageSize"], 3);
        assert_eq!(json["data"]["list"], serde_json::json!([1, 2, 3]));
    }

    // ── PageQuery ──

    #[test]
    fn page_query_clamps_bounds() {
        let q = PageQuery::new(0, 0);
        assert_eq!((q.page, q.page_size), (1, 1));
        let q = PageQuery::new(i64::MAX, i64::MAX);
        assert_eq!((q.page, q.page_size), (1_000_000, 1000));
        let q = PageQuery::new(-5, -10);
        assert_eq!((q.page, q.page_size), (1, 1));
    }

    #[test]
    fn page_query_from_query_defaults_and_types() {
        let q = PageQuery::from_query(None::<u64>, None::<u64>);
        assert_eq!((q.page, q.page_size), (1, 10));
        let q = PageQuery::from_query(Some(3u64), Some(50i64));
        assert_eq!((q.page, q.page_size), (3, 50));
        let q = PageQuery::from_query(Some(9_999_999u32), Some(0i32));
        assert_eq!((q.page, q.page_size), (1_000_000, 1));
    }

    #[test]
    fn page_query_offset_limit() {
        let q = PageQuery::new(3, 20);
        assert_eq!(q.offset(), 40);
        assert_eq!(q.limit(), 20);
        // 饱和乘法不溢出
        let q = PageQuery::new(1_000_000, 1000);
        assert_eq!(q.offset(), 999_999_000);
    }

    // ── ApiError 工厂方法 ──

    #[test]
    fn api_error_factories_status_and_code() {
        let cases: Vec<(ApiError, u16, i32)> = vec![
            (ApiError::bad_request("a"), 400, codes::BAD_REQUEST),
            (ApiError::unauthorized("a"), 401, codes::UNAUTHORIZED),
            (ApiError::forbidden("a"), 403, codes::FORBIDDEN),
            (ApiError::not_found("a"), 404, codes::NOT_FOUND),
            (ApiError::record_not_found("a"), 404, codes::RECORD_NOT_FOUND),
            (ApiError::method_not_allowed("a"), 405, codes::METHOD_NOT_ALLOWED),
            (ApiError::conflict("a"), 409, codes::CONFLICT),
            (ApiError::unprocessable_entity("a"), 422, codes::UNPROCESSABLE_ENTITY),
            (ApiError::too_many_requests("a"), 429, codes::TOO_MANY_REQUESTS),
            (ApiError::internal("a"), 500, codes::INTERNAL),
            (ApiError::service_unavailable("a"), 503, codes::SERVICE_UNAVAILABLE),
        ];
        for (e, status, code) in cases {
            assert_eq!(e.status, status);
            assert_eq!(e.code, code);
            assert_eq!(e.msg, "a");
        }
        // 两级 404:HTTP 状态相同,业务码必须可区分(路由 404 vs 记录 40401)
        assert_ne!(
            ApiError::not_found("a").code,
            ApiError::record_not_found("a").code,
            "路由级与记录级 404 必须可通过业务码区分"
        );
    }

    #[test]
    fn api_error_internal_masked_keeps_detail() {
        let e = ApiError::internal_masked("对外提示", "秘密内部栈");
        assert_eq!(e.status, 500);
        assert_eq!(e.msg, "对外提示");
        assert_eq!(e.internal_detail.as_deref(), Some("秘密内部栈"));
    }

    #[test]
    fn api_error_from_code_uses_registry() {
        let e = ApiError::from_code(ErrorCode::NotFound);
        assert_eq!(e.status, 404);
        assert_eq!(e.code, 404);
        assert_eq!(e.msg, error_message_of(ErrorCode::NotFound));

        let e = ApiError::from_code_detail(ErrorCode::Internal, "db down");
        assert_eq!(e.code, 500);
        assert_eq!(e.internal_detail.as_deref(), Some("db down"));
    }

    #[test]
    fn api_error_from_core_error_is_masked_500() {
        let e: ApiError = Error::Config("bad toml".into()).into();
        assert_eq!(e.status, 500);
        assert_eq!(e.code, codes::INTERNAL);
        // 对外消息来自注册表,不泄露内部细节
        assert_eq!(e.msg, error_message_of(ErrorCode::Internal));
        assert!(e.internal_detail.unwrap().contains("bad toml"));
    }

    #[test]
    fn api_error_display_and_std_error() {
        let e = ApiError::not_found("用户不存在");
        assert_eq!(e.to_string(), "[404] 用户不存在");
        let boxed: Box<dyn std::error::Error> = Box::new(e);
        assert!(boxed.to_string().contains("404"));
    }

    #[test]
    fn api_error_new_without_tracking() {
        let e = ApiError::new(418, -1, "teapot");
        assert_eq!((e.status, e.code), (418, -1));
        assert!(e.internal_detail.is_none());
    }

    #[test]
    fn trace_error_macro_produces_internal() {
        let io = std::io::Error::other("disk full");
        let e = trace_error!(io);
        assert_eq!(e.code, codes::INTERNAL);
        let e = trace_error!("plain", "上下文");
        assert_eq!(e.code, codes::INTERNAL);
    }

    // ── IntoResponse(需 web feature) ──

    #[cfg(feature = "axum")]
    mod web_responses {
        use super::*;
        use axum::body::to_bytes;
        use axum::http::StatusCode;

        #[tokio::test]
        async fn res_into_response_json_with_charset() {
            let resp = Res::ok("hi").into_response();
            assert_eq!(resp.status(), StatusCode::OK);
            assert_eq!(
                resp.headers()["content-type"],
                "application/json; charset=utf-8"
            );
            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(json["code"], 200);
            assert_eq!(json["data"], "hi");
        }

        #[tokio::test]
        async fn api_error_into_response_keeps_status_and_hides_detail() {
            let resp = ApiError::not_found("没找到").into_response();
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(json["code"], 404);
            assert_eq!(json["msg"], "没找到");
            assert!(json.get("data").is_none());
        }

        #[tokio::test]
        async fn api_error_invalid_status_falls_back_to_500() {
            // 非法 HTTP 状态码(超出 100..=999)回退为 500,业务码保留
            let resp = ApiError::new(1000, 12345, "x").into_response();
            assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
            let body = to_bytes(resp.into_body(), 1024).await.unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(json["code"], 12345);
        }
    }
}