use std::{
borrow::Cow,
collections::BTreeMap,
error::Error,
fmt::{self, Display, Formatter, Write as _},
};
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Serialize;
#[cfg(feature = "logging")]
use crate::observability::{Diagnostic, SqlDiagnostic};
const MAX_INTERNAL_ERROR_BYTES: usize = 16 * 1024;
#[cfg(feature = "logging")]
const MAX_SOURCE_ERROR_BYTES: usize = 4 * 1024;
#[cfg(feature = "logging")]
const MAX_SOURCE_DEPTH: usize = 16;
const MAX_CONTEXT_FIELDS: usize = 32;
const MAX_CONTEXT_KEY_BYTES: usize = 256;
const MAX_CONTEXT_VALUE_BYTES: usize = 4 * 1024;
#[cfg(feature = "logging")]
const MAX_DIAGNOSTICS: usize = 16;
const TRUNCATED_SUFFIX: &str = "…(已截断)";
#[derive(Debug, Default)]
struct InternalError {
error: Option<String>,
#[cfg(feature = "logging")]
source_chain: Vec<String>,
context: BTreeMap<String, String>,
#[cfg(feature = "logging")]
diagnostics: Vec<Diagnostic>,
}
#[cfg(feature = "logging")]
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ErrorLogMetadata {
pub(crate) code: u32,
#[serde(rename = "message")]
pub(crate) client_message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) internal_error: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub(crate) source_chain: Vec<String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub(crate) context: BTreeMap<String, String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub(crate) diagnostics: Vec<Diagnostic>,
}
#[cfg(feature = "logging")]
impl ErrorLogMetadata {
pub(crate) const fn has_internal_diagnostics(&self) -> bool {
self.internal_error.is_some()
|| !self.source_chain.is_empty()
|| !self.diagnostics.is_empty()
}
}
#[derive(Clone, Debug, Serialize)]
#[must_use = "应将统一成功响应返回给调用方"]
pub struct ApiResponse<T> {
pub code: u32,
pub data: T,
pub msg: Cow<'static, str>,
}
impl<T> ApiResponse<T> {
pub const fn new(data: T) -> Self {
Self {
code: 200,
data,
msg: Cow::Borrowed("操作成功"),
}
}
pub fn with_message(data: T, msg: impl Into<Cow<'static, str>>) -> Self {
Self {
code: 200,
data,
msg: msg.into(),
}
}
pub fn with_code(data: T, code: u32, msg: impl Into<Cow<'static, str>>) -> Self {
Self {
code,
data,
msg: msg.into(),
}
}
pub fn new_and_msg(data: T, msg: impl Into<Cow<'static, str>>) -> Self {
Self::with_message(data, msg)
}
pub fn into_data(self) -> T {
self.data
}
pub fn map<U>(self, mapper: impl FnOnce(T) -> U) -> ApiResponse<U> {
ApiResponse {
code: self.code,
data: mapper(self.data),
msg: self.msg,
}
}
}
impl<T> IntoResponse for ApiResponse<T>
where
T: Serialize,
{
fn into_response(self) -> Response {
(StatusCode::OK, Json(self)).into_response()
}
}
#[derive(Debug, Serialize)]
#[must_use = "应将统一错误响应返回给调用方或继续传播"]
pub struct ApiError {
pub code: u32,
pub msg: String,
#[serde(skip)]
http_status: StatusCode,
#[serde(skip)]
internal: Option<Box<InternalError>>,
}
impl ApiError {
pub fn new(code: u32, msg: impl Into<String>) -> Self {
Self {
code,
msg: msg.into(),
http_status: StatusCode::OK,
internal: None,
}
}
pub fn err_request_external_service(msg: impl Into<String>) -> Self {
Self::new(100_000, msg)
}
pub fn err_bad_request(msg: impl Into<String>) -> Self {
Self::new(400_000, msg)
}
pub fn err_invalid_param(msg: impl Into<String>) -> Self {
Self::new(400_001, msg)
}
pub fn err_token_client_invalid(msg: impl Into<String>) -> Self {
Self::new(400_002, msg)
}
pub fn err_token_server_invalid(msg: impl Into<String>) -> Self {
Self::new(400_003, msg)
}
pub fn err_unauthorized(msg: impl Into<String>) -> Self {
Self::new(401_000, msg)
}
pub fn err_forbidden_auth(msg: impl Into<String>) -> Self {
Self::new(403_000, msg)
}
pub fn err_user_disabled(msg: impl Into<String>) -> Self {
Self::new(403_001, msg)
}
pub fn err_not_found(msg: impl Into<String>) -> Self {
Self::new(404_000, msg)
}
pub fn err_data_exists(msg: impl Into<String>) -> Self {
Self::new(409_000, msg)
}
pub fn err_unique_index_conflict(msg: impl Into<String>) -> Self {
Self::new(409_001, msg)
}
pub fn err_version_conflict(msg: impl Into<String>) -> Self {
Self::new(409_002, msg)
}
pub fn err_foreign_key_conflict(msg: impl Into<String>) -> Self {
Self::new(409_003, msg)
}
pub fn err_constraint_conflict(msg: impl Into<String>) -> Self {
Self::new(409_004, msg)
}
pub fn err_server_busy(msg: impl Into<String>) -> Self {
Self::new(500_000, msg)
}
pub fn err_database(msg: impl Into<String>) -> Self {
Self::new(500_001, msg)
}
pub fn err_redis(msg: impl Into<String>) -> Self {
Self::new(500_002, msg)
}
pub fn err_encrypt(msg: impl Into<String>) -> Self {
Self::new(600_000, msg)
}
pub fn err_other(msg: impl Into<String>) -> Self {
Self::new(999_999, msg)
}
pub fn with_error(mut self, error: impl Display) -> Self {
self.internal
.get_or_insert_with(|| Box::new(InternalError::default()))
.error = Some(bounded_display(&error, MAX_INTERNAL_ERROR_BYTES));
self
}
pub fn with_source<E>(mut self, error: &E) -> Self
where
E: Error + ?Sized,
{
let internal = self
.internal
.get_or_insert_with(|| Box::new(InternalError::default()));
internal.error = Some(bounded_display(error, MAX_INTERNAL_ERROR_BYTES));
#[cfg(feature = "logging")]
{
internal.source_chain.clear();
let mut source = error.source();
while let Some(current) = source
&& internal.source_chain.len() < MAX_SOURCE_DEPTH
{
internal
.source_chain
.push(bounded_display(current, MAX_SOURCE_ERROR_BYTES));
source = current.source();
}
if source.is_some() {
internal.source_chain.push("…(来源链已截断)".to_owned());
}
}
self
}
#[cfg(feature = "logging")]
pub fn with_diagnostic(mut self, diagnostic: impl Into<Diagnostic>) -> Self {
let diagnostics = &mut self
.internal
.get_or_insert_with(|| Box::new(InternalError::default()))
.diagnostics;
if diagnostics.len() < MAX_DIAGNOSTICS {
diagnostics.push(diagnostic.into().bounded_for_log());
}
self
}
#[cfg(feature = "logging")]
pub fn with_sql_error(self, diagnostic: SqlDiagnostic) -> Self {
self.with_diagnostic(diagnostic)
}
pub const fn with_http_status(mut self, status: StatusCode) -> Self {
self.http_status = status;
self
}
pub fn with_context(mut self, key: impl Into<String>, value: impl Display) -> Self {
let key = truncate_owned(key.into(), MAX_CONTEXT_KEY_BYTES);
let internal = self
.internal
.get_or_insert_with(|| Box::new(InternalError::default()));
if internal.context.contains_key(&key) || internal.context.len() < MAX_CONTEXT_FIELDS {
internal
.context
.insert(key, bounded_display(&value, MAX_CONTEXT_VALUE_BYTES));
}
self
}
#[must_use]
pub const fn http_status(&self) -> StatusCode {
self.http_status
}
#[must_use]
pub fn internal_error(&self) -> Option<&str> {
self.internal
.as_ref()
.and_then(|internal| internal.error.as_deref())
}
#[must_use]
pub fn internal_context(&self) -> Option<&BTreeMap<String, String>> {
self.internal.as_ref().map(|internal| &internal.context)
}
#[cfg(feature = "logging")]
#[must_use]
pub fn diagnostics(&self) -> Option<&[Diagnostic]> {
self.internal
.as_ref()
.map(|internal| internal.diagnostics.as_slice())
}
}
fn truncate_owned(mut value: String, max_bytes: usize) -> String {
if value.len() <= max_bytes {
return value;
}
let mut boundary = max_bytes.saturating_sub(TRUNCATED_SUFFIX.len());
while boundary > 0 && !value.is_char_boundary(boundary) {
boundary -= 1;
}
value.truncate(boundary);
value.push_str(TRUNCATED_SUFFIX);
value
}
fn bounded_display<T>(value: &T, max_bytes: usize) -> String
where
T: Display + ?Sized,
{
let mut writer = LimitedStringWriter {
output: String::with_capacity(max_bytes.min(256)),
max_bytes,
truncated: false,
};
let _ = write!(&mut writer, "{value}");
if writer.truncated {
let keep = max_bytes.saturating_sub(TRUNCATED_SUFFIX.len());
truncate_to_boundary(&mut writer.output, keep);
if max_bytes >= TRUNCATED_SUFFIX.len() {
writer.output.push_str(TRUNCATED_SUFFIX);
}
}
writer.output
}
struct LimitedStringWriter {
output: String,
max_bytes: usize,
truncated: bool,
}
impl fmt::Write for LimitedStringWriter {
fn write_str(&mut self, value: &str) -> fmt::Result {
let remaining = self.max_bytes.saturating_sub(self.output.len());
if value.len() <= remaining {
self.output.push_str(value);
return Ok(());
}
let mut boundary = remaining;
while boundary > 0 && !value.is_char_boundary(boundary) {
boundary -= 1;
}
self.output.push_str(&value[..boundary]);
self.truncated = true;
Err(fmt::Error)
}
}
fn truncate_to_boundary(value: &mut String, max_bytes: usize) {
let mut boundary = max_bytes.min(value.len());
while boundary > 0 && !value.is_char_boundary(boundary) {
boundary -= 1;
}
value.truncate(boundary);
}
impl Display for ApiError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}(业务码:{})", self.msg, self.code)
}
}
impl Error for ApiError {}
#[cfg(feature = "connection")]
impl From<crate::connection::ConnectionUnavailable> for ApiError {
fn from(error: crate::connection::ConnectionUnavailable) -> Self {
let connector = error.connector().to_owned();
Self::err_server_busy("依赖服务暂时不可用,请稍后重试")
.with_source(&error)
.with_context("connector", connector)
}
}
#[cfg(feature = "connection")]
impl<E> From<crate::connection::ManagedConnectionError<E>> for ApiError
where
E: Error + 'static,
{
fn from(error: crate::connection::ManagedConnectionError<E>) -> Self {
Self::err_server_busy("依赖服务健康检查失败,请稍后重试").with_source(&error)
}
}
#[cfg(any(
feature = "connection-mysql",
feature = "connection-postgres",
feature = "connection-redis",
feature = "connection-kafka",
feature = "connection-etcd",
feature = "connection-mqtt",
feature = "connection-elasticsearch"
))]
impl From<crate::connection::ConnectionError> for ApiError {
fn from(error: crate::connection::ConnectionError) -> Self {
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
if matches!(
&error,
crate::connection::ConnectionError::InvalidPoolOptions(_)
| crate::connection::ConnectionError::Sqlx(_)
) {
return Self::err_database("数据库操作失败,请稍后重试").with_source(&error);
}
#[cfg(feature = "connection-redis")]
if matches!(
&error,
crate::connection::ConnectionError::Redis(_)
| crate::connection::ConnectionError::UnexpectedRedisPing(_)
) {
return Self::err_redis("Redis 操作失败,请稍后重试").with_source(&error);
}
Self::err_server_busy("依赖服务操作失败,请稍后重试").with_source(&error)
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SqlErrorClass {
NotFound,
UniqueViolation,
ForeignKeyViolation,
NotNullViolation,
CheckViolation,
PoolUnavailable,
Connection,
Decode,
Database,
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl SqlErrorClass {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::NotFound => "not_found",
Self::UniqueViolation => "unique_violation",
Self::ForeignKeyViolation => "foreign_key_violation",
Self::NotNullViolation => "not_null_violation",
Self::CheckViolation => "check_violation",
Self::PoolUnavailable => "pool_unavailable",
Self::Connection => "connection",
Self::Decode => "decode",
Self::Database => "database",
}
}
#[must_use]
pub fn classify(error: &sqlx::Error) -> Self {
use sqlx::error::ErrorKind;
match error {
sqlx::Error::RowNotFound => Self::NotFound,
sqlx::Error::Database(error) => match error.kind() {
ErrorKind::UniqueViolation => Self::UniqueViolation,
ErrorKind::ForeignKeyViolation => Self::ForeignKeyViolation,
ErrorKind::NotNullViolation => Self::NotNullViolation,
ErrorKind::CheckViolation | ErrorKind::ExclusionViolation => Self::CheckViolation,
_ => Self::Database,
},
sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => Self::PoolUnavailable,
sqlx::Error::Io(_)
| sqlx::Error::Tls(_)
| sqlx::Error::Protocol(_)
| sqlx::Error::WorkerCrashed
| sqlx::Error::BeginFailed => Self::Connection,
sqlx::Error::ColumnIndexOutOfBounds { .. }
| sqlx::Error::ColumnNotFound(_)
| sqlx::Error::ColumnDecode { .. }
| sqlx::Error::Encode(_)
| sqlx::Error::Decode(_) => Self::Decode,
_ => Self::Database,
}
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
pub(crate) fn default_sqlx_api_error(error: &sqlx::Error) -> ApiError {
match SqlErrorClass::classify(error) {
SqlErrorClass::NotFound => ApiError::err_not_found("数据不存在"),
SqlErrorClass::UniqueViolation => ApiError::err_unique_index_conflict("数据已存在"),
SqlErrorClass::PoolUnavailable => ApiError::err_server_busy("数据库连接繁忙,请稍后重试"),
SqlErrorClass::ForeignKeyViolation
| SqlErrorClass::NotNullViolation
| SqlErrorClass::CheckViolation
| SqlErrorClass::Connection
| SqlErrorClass::Decode
| SqlErrorClass::Database => ApiError::err_database("数据库操作失败,请稍后重试"),
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl From<sqlx::Error> for ApiError {
fn from(error: sqlx::Error) -> Self {
default_sqlx_api_error(&error).with_source(&error)
}
}
#[cfg(feature = "connection-redis")]
impl From<redis::RedisError> for ApiError {
fn from(error: redis::RedisError) -> Self {
Self::err_redis("Redis 操作失败,请稍后重试").with_source(&error)
}
}
#[cfg(feature = "connection-kafka")]
impl From<rdkafka::error::KafkaError> for ApiError {
fn from(error: rdkafka::error::KafkaError) -> Self {
Self::err_server_busy("Kafka 操作失败,请稍后重试")
.with_source(&error)
.with_context("connector", "kafka")
}
}
#[cfg(feature = "connection-kafka")]
impl From<(rdkafka::error::KafkaError, rdkafka::message::OwnedMessage)> for ApiError {
fn from(
(error, _message): (rdkafka::error::KafkaError, rdkafka::message::OwnedMessage),
) -> Self {
Self::from(error)
}
}
#[cfg(feature = "connection-etcd")]
impl From<etcd_client::Error> for ApiError {
fn from(error: etcd_client::Error) -> Self {
Self::err_server_busy("etcd 操作失败,请稍后重试")
.with_source(&error)
.with_context("connector", "etcd")
}
}
#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::ClientError> for ApiError {
fn from(error: rumqttc::ClientError) -> Self {
Self::err_server_busy("MQTT 操作失败,请稍后重试")
.with_source(&error)
.with_context("connector", "mqtt")
}
}
#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::ConnectionError> for ApiError {
fn from(error: rumqttc::ConnectionError) -> Self {
Self::err_server_busy("MQTT 连接失败,请稍后重试")
.with_source(&error)
.with_context("connector", "mqtt")
}
}
#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::OptionError> for ApiError {
fn from(error: rumqttc::OptionError) -> Self {
Self::err_server_busy("MQTT 配置无效,请检查服务配置")
.with_source(&error)
.with_context("connector", "mqtt")
}
}
#[cfg(feature = "connection-elasticsearch")]
impl From<elasticsearch::Error> for ApiError {
fn from(error: elasticsearch::Error) -> Self {
Self::err_server_busy("Elasticsearch 操作失败,请稍后重试")
.with_source(&error)
.with_context("connector", "elasticsearch")
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
#[cfg(feature = "logging")]
{
let status = self.http_status;
let mut response = (status, Json(&self)).into_response();
let Self {
code,
msg,
internal,
..
} = self;
let InternalError {
error,
source_chain,
context,
diagnostics,
} = internal.map(|internal| *internal).unwrap_or_default();
let metadata = ErrorLogMetadata {
code,
client_message: msg,
internal_error: error,
source_chain,
context,
diagnostics,
};
response.extensions_mut().insert(metadata);
response
}
#[cfg(not(feature = "logging"))]
{
(self.http_status, Json(self)).into_response()
}
}
}
pub type ApiResult<T> = Result<ApiResponse<T>, ApiError>;
pub type AppOk<T> = ApiResponse<T>;
pub type AppError = ApiError;
pub type AppResult<T> = ApiResult<T>;
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use axum::response::IntoResponse;
use http_body_util::BodyExt;
use super::*;
#[cfg(feature = "connection")]
#[test]
fn unavailable_connection_converts_to_safe_api_error() {
let source = crate::connection::ConnectionUnavailable::new("primary-mysql");
let error = ApiError::from(source);
assert_eq!(error.code, 500_000);
assert_eq!(error.msg, "依赖服务暂时不可用,请稍后重试");
assert_eq!(
error.internal_error(),
Some("连接 `primary-mysql` 未启用,无法执行操作")
);
assert_eq!(
error.internal_context().unwrap().get("connector"),
Some(&"primary-mysql".to_owned())
);
}
#[cfg(feature = "connection")]
#[test]
fn managed_connection_error_converts_to_safe_api_error() {
let source = crate::connection::ManagedConnectionError::<std::io::Error>::Unavailable(
crate::connection::ConnectionUnavailable::new("custom"),
);
let error = ApiError::from(source);
assert_eq!(error.code, 500_000);
assert_eq!(error.msg, "依赖服务健康检查失败,请稍后重试");
assert_eq!(
error.internal_error(),
Some("连接 `custom` 未启用,无法执行操作")
);
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[test]
fn sqlx_row_not_found_converts_to_not_found_api_error() {
let error = ApiError::from(sqlx::Error::RowNotFound);
assert_eq!(error.code, 404_000);
assert_eq!(error.msg, "数据不存在");
assert!(
error
.internal_error()
.is_some_and(|message| message.contains("no rows returned"))
);
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[derive(Debug)]
struct UniqueDatabaseError;
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl Display for UniqueDatabaseError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("唯一索引冲突")
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl Error for UniqueDatabaseError {}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl sqlx::error::DatabaseError for UniqueDatabaseError {
fn message(&self) -> &str {
"唯一索引冲突"
}
fn code(&self) -> Option<Cow<'_, str>> {
Some(Cow::Borrowed("23505"))
}
fn constraint(&self) -> Option<&str> {
Some("uk_users_email")
}
fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {
self
}
fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {
self
}
fn into_error(self: Box<Self>) -> Box<dyn Error + Send + Sync + 'static> {
self
}
fn kind(&self) -> sqlx::error::ErrorKind {
sqlx::error::ErrorKind::UniqueViolation
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[test]
fn sqlx_unique_violation_converts_to_conflict_api_error() {
let source = sqlx::Error::Database(Box::new(UniqueDatabaseError));
assert_eq!(
SqlErrorClass::classify(&source),
SqlErrorClass::UniqueViolation
);
let error = ApiError::from(source);
assert_eq!(error.code, 409_001);
assert_eq!(error.msg, "数据已存在");
assert!(
error
.internal_error()
.is_some_and(|message| message.contains("唯一索引冲突"))
);
}
#[cfg(feature = "connection-redis")]
#[test]
fn redis_error_converts_to_safe_redis_api_error() {
let source = redis::RedisError::from((redis::ErrorKind::Client, "Redis 测试错误"));
let error = ApiError::from(source);
assert_eq!(error.code, 500_002);
assert_eq!(error.msg, "Redis 操作失败,请稍后重试");
assert!(
error
.internal_error()
.is_some_and(|message| message.contains("Redis 测试错误"))
);
}
#[cfg(any(
feature = "connection-mysql",
feature = "connection-postgres",
feature = "connection-redis",
feature = "connection-kafka",
feature = "connection-etcd",
feature = "connection-mqtt",
feature = "connection-elasticsearch"
))]
#[test]
fn all_builtin_connection_errors_support_question_mark_propagation() {
fn assert_into_api_error<E: Into<ApiError>>() {}
assert_into_api_error::<crate::connection::ConnectionError>();
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
assert_into_api_error::<sqlx::Error>();
#[cfg(feature = "connection-redis")]
assert_into_api_error::<redis::RedisError>();
#[cfg(feature = "connection-kafka")]
{
assert_into_api_error::<rdkafka::error::KafkaError>();
assert_into_api_error::<(rdkafka::error::KafkaError, rdkafka::message::OwnedMessage)>();
}
#[cfg(feature = "connection-etcd")]
assert_into_api_error::<etcd_client::Error>();
#[cfg(feature = "connection-mqtt")]
{
assert_into_api_error::<rumqttc::ClientError>();
assert_into_api_error::<rumqttc::ConnectionError>();
assert_into_api_error::<rumqttc::OptionError>();
}
#[cfg(feature = "connection-elasticsearch")]
assert_into_api_error::<elasticsearch::Error>();
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[test]
fn shared_connection_error_preserves_database_classification() {
let error = ApiError::from(crate::connection::ConnectionError::Sqlx(
sqlx::Error::RowNotFound,
));
assert_eq!(error.code, 500_001);
assert_eq!(error.msg, "数据库操作失败,请稍后重试");
assert!(
error
.internal_error()
.is_some_and(|message| message.contains("数据库连接失败"))
);
}
#[tokio::test]
async fn success_response_uses_expected_json_shape() {
let response = ApiResponse::new("数据").into_response();
let body = response.into_body().collect().await.unwrap().to_bytes();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["code"], 200);
assert_eq!(value["data"], "数据");
assert_eq!(value["msg"], "操作成功");
}
#[test]
fn default_success_message_does_not_allocate() {
let response = ApiResponse::new(1);
assert!(matches!(response.msg, Cow::Borrowed("操作成功")));
assert_eq!(response.map(|value| value + 1).into_data(), 2);
}
#[test]
fn success_constructors_preserve_code_data_and_message() {
let with_message = ApiResponse::with_message(1, "创建完成");
assert_eq!(with_message.code, 200);
assert_eq!(with_message.data, 1);
assert_eq!(with_message.msg, "创建完成");
let with_code = ApiResponse::with_code(2, 201, "已创建");
assert_eq!(with_code.code, 201);
assert_eq!(with_code.data, 2);
assert_eq!(with_code.msg, "已创建");
let alias = ApiResponse::new_and_msg(3, "兼容接口");
assert_eq!(alias.code, 200);
assert_eq!(alias.data, 3);
assert_eq!(alias.msg, "兼容接口");
}
#[tokio::test]
async fn internal_error_hides_details_from_client() {
let response = ApiError::err_database("查询失败")
.with_error("数据库连接被拒绝")
.with_context("user_id", 1001)
.into_response();
let body = response.into_body().collect().await.unwrap().to_bytes();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["msg"], "查询失败");
assert!(value.get("internal").is_none());
assert!(!String::from_utf8_lossy(&body).contains("数据库连接被拒绝"));
}
#[test]
fn constructors_use_expected_business_codes() {
assert_eq!(ApiError::new(400_099, "自定义错误").code, 400_099);
assert_eq!(ApiError::err_request_external_service("错误").code, 100_000);
assert_eq!(ApiError::err_bad_request("错误").code, 400_000);
assert_eq!(ApiError::err_invalid_param("错误").code, 400_001);
assert_eq!(ApiError::err_token_client_invalid("错误").code, 400_002);
assert_eq!(ApiError::err_token_server_invalid("错误").code, 400_003);
assert_eq!(ApiError::err_unauthorized("错误").code, 401_000);
assert_eq!(ApiError::err_forbidden_auth("错误").code, 403_000);
assert_eq!(ApiError::err_user_disabled("错误").code, 403_001);
assert_eq!(ApiError::err_not_found("错误").code, 404_000);
assert_eq!(ApiError::err_data_exists("错误").code, 409_000);
assert_eq!(ApiError::err_unique_index_conflict("错误").code, 409_001);
assert_eq!(ApiError::err_version_conflict("错误").code, 409_002);
assert_eq!(ApiError::err_foreign_key_conflict("错误").code, 409_003);
assert_eq!(ApiError::err_constraint_conflict("错误").code, 409_004);
assert_eq!(ApiError::err_server_busy("错误").code, 500_000);
assert_eq!(ApiError::err_database("错误").code, 500_001);
assert_eq!(ApiError::err_redis("错误").code, 500_002);
assert_eq!(ApiError::err_encrypt("错误").code, 600_000);
assert_eq!(ApiError::err_other("错误").code, 999_999);
}
#[derive(Debug)]
struct CyclicError;
impl Display for CyclicError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter.write_str("循环错误")
}
}
impl Error for CyclicError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(self)
}
}
#[cfg(feature = "logging")]
#[test]
fn internal_metadata_is_bounded() {
let mut error = ApiError::err_other("失败")
.with_error("错误".repeat(MAX_INTERNAL_ERROR_BYTES))
.with_source(&CyclicError);
for index in 0..(MAX_CONTEXT_FIELDS + 10) {
error = error.with_context(format!("field-{index}"), "值");
}
for index in 0..(MAX_DIAGNOSTICS + 10) {
error = error.with_diagnostic(Diagnostic::new(
crate::observability::DiagnosticKind::Internal,
format!("diagnostic-{index}"),
"错误",
));
}
let internal = error.internal.as_ref().unwrap();
assert!(internal.error.as_ref().unwrap().len() <= MAX_INTERNAL_ERROR_BYTES);
assert_eq!(internal.source_chain.len(), MAX_SOURCE_DEPTH + 1);
assert_eq!(internal.context.len(), MAX_CONTEXT_FIELDS);
assert_eq!(internal.diagnostics.len(), MAX_DIAGNOSTICS);
}
#[test]
fn api_error_keeps_large_diagnostics_behind_a_pointer() {
assert!(std::mem::size_of::<ApiError>() <= 64);
}
#[test]
fn internal_error_and_context_support_chaining() {
let error = ApiError::err_bad_request("这是 msg 信息")
.with_error("真实错误")
.with_context("key", "value")
.with_context("request_id", 1001);
assert_eq!(error.msg, "这是 msg 信息");
assert_eq!(error.internal_error(), Some("真实错误"));
let context = error.internal_context().unwrap();
assert_eq!(context.get("key").map(String::as_str), Some("value"));
assert_eq!(context.get("request_id").map(String::as_str), Some("1001"));
}
#[test]
fn context_can_be_added_before_error_and_duplicate_keys_are_replaced() {
let error = ApiError::err_database("查询失败")
.with_context("operation", "旧值")
.with_context("operation", "查询用户")
.with_error("连接超时");
assert_eq!(error.internal_error(), Some("连接超时"));
assert_eq!(
error
.internal_context()
.and_then(|context| context.get("operation"))
.map(String::as_str),
Some("查询用户")
);
}
#[cfg(feature = "logging")]
#[test]
fn response_extension_receives_owned_internal_metadata() {
let response = ApiError::err_database("查询失败")
.with_error("连接超时")
.with_context("operation", "查询用户")
.into_response();
let metadata = response.extensions().get::<ErrorLogMetadata>().unwrap();
assert_eq!(metadata.code, 500_001);
assert_eq!(metadata.client_message, "查询失败");
assert_eq!(metadata.internal_error.as_deref(), Some("连接超时"));
assert_eq!(
metadata.context.get("operation").map(String::as_str),
Some("查询用户")
);
}
}