#[non_exhaustive]pub struct ApiResponse {
pub code: i32,
pub message: String,
pub data: Option<Value>,
pub attachment: Option<ResponseAttachment>,
/* private fields */
}Expand description
API 响应
统一的 API 响应格式,用于所有 Action 的返回值
§字段
code: 状态码(0 表示成功,非零表示失败)message: 响应消息data: 响应数据(可选)
标注 #[non_exhaustive]:未来新增字段不构成破坏性变更。
请使用 ApiResponse::success / ApiResponse::fail / ApiResponse::from_error 等构造。
§示例
use yang_base::action::ApiResponse;
use serde_json::json;
// 创建成功响应
let response = ApiResponse::success(
json!({ "id": 123, "name": "Alice" }),
"操作成功"
);
assert_eq!(response.code, 0);
// 创建失败响应
let response = ApiResponse::fail(400001, "参数错误");
assert_eq!(response.code, 400001);
assert!(response.data.is_none());Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.code: i32状态码
- 0: 成功
- 非零: 失败(具体错误码由业务定义)
message: String响应消息
描述操作结果的文本信息
data: Option<Value>响应数据
成功时包含业务数据,失败时通常为 None
attachment: Option<ResponseAttachment>非 JSON 附件(文件下载/预览/重定向),由传输层消费。
仅当 Action 以 ResponseBody 为输出时由派发边界填充;
serde(skip) 保证普通 Action 的 JSON 线格式不受影响。
Implementations§
Source§impl ApiResponse
impl ApiResponse
Sourcepub fn success<T: Serialize>(
data: T,
message: impl Into<String>,
) -> Result<Self, BaseError>
pub fn success<T: Serialize>( data: T, message: impl Into<String>, ) -> Result<Self, BaseError>
创建成功响应
状态码为 0,包含业务数据。序列化失败时返回 BaseError::JsonSerializeFailed。
§参数
data: 响应数据(任何可序列化的类型)message: 成功消息
§返回
Ok(ApiResponse): 序列化成功时返回响应实例Err(BaseError::JsonSerializeFailed): 序列化失败时返回错误
§Errors
BaseError::JsonSerializeFailed: 当data无法被序列化为 JSON 时
§示例
use yang_base::action::ApiResponse;
use serde_json::json;
// 返回单个对象
let response = ApiResponse::success(
json!({ "id": 1, "name": "Alice" }),
"获取成功"
)?;
// 返回影响行数
let response = ApiResponse::success(
json!({ "affected": 1 }),
"更新成功"
)?;Sourcepub fn success_value(data: Value, message: impl Into<String>) -> Self
pub fn success_value(data: Value, message: impl Into<String>) -> Self
创建成功响应(接受已序列化的 JSON 值)
当数据已经是 serde_json::Value 类型时,使用此方法可避免额外的序列化开销,
且不会失败,因此直接返回 Self 而非 Result。
§参数
data: 已序列化的 JSON 值message: 成功消息
§返回
- ApiResponse 实例
§示例
use yang_base::action::ApiResponse;
use serde_json::json;
// 直接使用 serde_json::Value
let data = json!({ "id": 1, "name": "Alice" });
let response = ApiResponse::success_value(data, "获取成功");
assert_eq!(response.code, 0);Sourcepub fn fail(code: i32, message: impl Into<String>) -> Self
pub fn fail(code: i32, message: impl Into<String>) -> Self
创建失败响应
状态码为非零错误码,不包含数据
§参数
code: 错误码(非零整数)message: 错误消息
§返回
- ApiResponse 实例
§示例
use yang_base::action::ApiResponse;
// 参数错误
let response = ApiResponse::fail(400001, "参数缺失: username");
// 权限错误
let response = ApiResponse::fail(403001, "权限不足");
// 业务错误
let response = ApiResponse::fail(500001, "用户名已存在");Sourcepub fn fail_value(code: i32, data: Value, message: impl Into<String>) -> Self
pub fn fail_value(code: i32, data: Value, message: impl Into<String>) -> Self
创建携带诊断数据的失败响应。
与 ApiResponse::fail(data 恒为空)相对,保留 data 载荷,
供就绪探针等需要自描述失败原因的端点使用。
Sourcepub fn attachment(
attachment: ResponseAttachment,
message: impl Into<String>,
) -> Self
pub fn attachment( attachment: ResponseAttachment, message: impl Into<String>, ) -> Self
创建携带附件的成功响应
由派发边界在识别到 Action 返回 ResponseBody 时调用。data 为 None,
附件信息仅对传输层可见(serde(skip)),JSON 线格式保持不变。
§参数
attachment: 传输层消费的附件描述message: 成功消息
§返回
- ApiResponse 实例
Sourcepub fn with_http_status(self, status: u16) -> Result<Self, BaseError>
pub fn with_http_status(self, status: u16) -> Result<Self, BaseError>
覆盖 Action 静态声明的成功 HTTP 状态码。
Sourcepub fn with_header(
self,
name: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, BaseError>
pub fn with_header( self, name: impl Into<String>, value: impl Into<String>, ) -> Result<Self, BaseError>
追加一个经过最小 RFC 语法校验的响应头。
使用列表而不是 Map,以保留多个 Set-Cookie 等同名响应头。
Sourcepub fn response_headers(&self) -> &[(String, String)]
pub fn response_headers(&self) -> &[(String, String)]
返回 Action 显式追加、由传输层消费的响应头。
响应头不参与 ApiResponse 的 JSON 序列化;此只读视图主要用于
传输适配器、集成测试以及需要检查 Cookie/缓存契约的应用层边界。
Sourcepub fn from_error(error: &BaseError) -> Self
pub fn from_error(error: &BaseError) -> Self
从 BaseError 创建失败响应
自动提取错误码和错误消息。接受引用以避免消费 BaseError 所有权,
调用方可在构建响应的同时保留 error 用于日志记录等后续用途。
§参数
error: BaseError 引用
§返回
- ApiResponse 实例
§示例
use yang_base::action::ApiResponse;
use yang_base::error::BaseError;
let error = BaseError::FieldRequired("username".to_string());
let response = ApiResponse::from_error(&error);
assert_ne!(response.code, 0);
assert!(response.message.contains("username"));
assert!(response.data.is_none());Trait Implementations§
Source§impl Clone for ApiResponse
impl Clone for ApiResponse
Source§impl Debug for ApiResponse
impl Debug for ApiResponse
Source§impl JsonSchema for ApiResponse
impl JsonSchema for ApiResponse
Source§fn schema_name() -> String
fn schema_name() -> String
Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
Source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
$ref keyword. Read moreAuto Trait Implementations§
impl Forget for ApiResponse
impl Freeze for ApiResponse
impl Move for ApiResponse
impl RefUnwindSafe for ApiResponse
impl Send for ApiResponse
impl Sync for ApiResponse
impl Unpin for ApiResponse
impl UnsafeUnpin for ApiResponse
impl UnwindSafe for ApiResponse
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more