1use 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
17pub 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 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#[derive(Debug, Clone, Serialize)]
43pub struct Res<T: Serialize = ()> {
44 pub code: i32,
46 pub msg: String,
48 #[serde(skip_serializing_if = "Option::is_none")]
50 pub data: Option<T>,
51}
52
53#[derive(Debug, Clone, Serialize)]
55pub struct PageData<T: Serialize> {
56 pub list: T,
58 pub total: i64,
60 pub page: i64,
62 #[serde(rename = "pageSize")]
64 pub page_size: i64,
65}
66
67pub type ResResult<T> = std::result::Result<Res<T>, ApiError>;
69
70#[derive(Debug, Clone, serde::Deserialize)]
74pub struct PageQuery {
75 pub page: i64,
77 pub page_size: i64,
79}
80
81impl PageQuery {
82 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 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 pub fn offset(&self) -> i64 {
115 (self.page - 1).saturating_mul(self.page_size)
116 }
117 pub fn limit(&self) -> i64 {
119 self.page_size
120 }
121}
122
123impl Res<()> {
126 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 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 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 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 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 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#[derive(Debug)]
205pub struct ApiError {
206 pub code: i32,
208 pub msg: Cow<'static, str>,
210 pub status: u16,
212 pub internal_detail: Option<String>,
214 pub source_location: Option<String>,
216}
217
218impl ApiError {
219 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 fn with_detail(mut self, detail: impl Into<String>) -> Self {
236 self.internal_detail = Some(detail.into());
237 self
238 }
239
240 #[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 #[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 #[track_caller]
266 pub fn unauthorized(msg: impl Into<Cow<'static, str>>) -> Self {
267 Self::tracked(401, codes::UNAUTHORIZED, msg)
268 }
269
270 #[track_caller]
272 pub fn forbidden(msg: impl Into<Cow<'static, str>>) -> Self {
273 Self::tracked(403, codes::FORBIDDEN, msg)
274 }
275
276 #[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 #[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 #[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 #[track_caller]
304 pub fn conflict(msg: impl Into<Cow<'static, str>>) -> Self {
305 Self::tracked(409, codes::CONFLICT, msg)
306 }
307
308 #[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 #[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 #[track_caller]
324 pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
325 Self::tracked(500, codes::INTERNAL, msg)
326 }
327
328 #[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 #[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 #[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 #[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 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 tracing::error!(target: "wordval_sqlx_error", detail = %detail, "SQL 查询异常");
407 ApiError::internal_masked(error_message_of(ErrorCode::Internal), detail)
408 }
409}
410
411#[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 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#[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 #[test]
496 fn error_api_roundtrip_preserves_status_and_code() {
497 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 let internal = ApiError::from(Error::Msg("数据库连接失败细节".into()));
508 assert_eq!(internal.status, 500);
509 assert_ne!(internal.msg, "数据库连接失败细节");
510 }
511
512 #[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 #[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 let q = PageQuery::new(1_000_000, 1000);
591 assert_eq!(q.offset(), 999_999_000);
592 }
593
594 #[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 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 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 #[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 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}