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},
};
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;
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;
}
#[derive(Debug, Clone, Serialize)]
pub struct Res<T: Serialize = ()> {
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,
}
pub type ResResult<T> = std::result::Result<Res<T>, ApiError>;
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PageQuery {
pub page: i64,
pub page_size: i64,
}
impl PageQuery {
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 }
}
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 }
}
pub fn offset(&self) -> i64 {
(self.page - 1).saturating_mul(self.page_size)
}
pub fn limit(&self) -> i64 {
self.page_size
}
}
impl Res<()> {
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> {
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),
}
}
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,
})
}
}
#[derive(Debug)]
pub struct ApiError {
pub code: i32,
pub msg: Cow<'static, str>,
pub status: u16,
pub internal_detail: Option<String>,
pub source_location: Option<String>,
}
impl ApiError {
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
}
#[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
}
#[track_caller]
pub fn bad_request(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(400, codes::BAD_REQUEST, msg)
}
#[track_caller]
pub fn unauthorized(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(401, codes::UNAUTHORIZED, msg)
}
#[track_caller]
pub fn forbidden(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(403, codes::FORBIDDEN, msg)
}
#[track_caller]
pub fn not_found(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(404, codes::NOT_FOUND, msg)
}
#[track_caller]
pub fn record_not_found(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(404, codes::RECORD_NOT_FOUND, msg)
}
#[track_caller]
pub fn method_not_allowed(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(405, codes::METHOD_NOT_ALLOWED, msg)
}
#[track_caller]
pub fn conflict(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(409, codes::CONFLICT, msg)
}
#[track_caller]
pub fn unprocessable_entity(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(422, codes::UNPROCESSABLE_ENTITY, msg)
}
#[track_caller]
pub fn too_many_requests(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(429, codes::TOO_MANY_REQUESTS, msg)
}
#[track_caller]
pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(500, codes::INTERNAL, msg)
}
#[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)
}
#[track_caller]
pub fn service_unavailable(msg: impl Into<Cow<'static, str>>) -> Self {
Self::tracked(503, codes::SERVICE_UNAVAILABLE, msg)
}
#[track_caller]
pub fn from_code(code: ErrorCode) -> Self {
Self::tracked(code.http_status(), code as i32, error_message_of(code))
}
#[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 {
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();
tracing::error!(target: "wordval_sqlx_error", detail = %detail, "SQL 查询异常");
ApiError::internal_masked(error_message_of(ErrorCode::Internal), detail)
}
}
#[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) => {{
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))
}};
}
#[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;
#[test]
fn error_api_roundtrip_preserves_status_and_code() {
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, "往返必须保留业务码");
let internal = ApiError::from(Error::Msg("数据库连接失败细节".into()));
assert_eq!(internal.status, 500);
assert_ne!(internal.msg, "数据库连接失败细节");
}
#[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]));
}
#[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);
}
#[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");
}
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);
}
#[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() {
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);
}
}
}