Skip to main content

ApiResponse

Struct ApiResponse 

Source
#[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
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional 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

Source

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 }),
    "更新成功"
)?;
Source

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);
Source

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, "用户名已存在");
Source

pub fn fail_value(code: i32, data: Value, message: impl Into<String>) -> Self

创建携带诊断数据的失败响应。

与 ApiResponse::fail(data 恒为空)相对,保留 data 载荷, 供就绪探针等需要自描述失败原因的端点使用。

Source

pub fn attachment( attachment: ResponseAttachment, message: impl Into<String>, ) -> Self

创建携带附件的成功响应

由派发边界在识别到 Action 返回 ResponseBody 时调用。data 为 None, 附件信息仅对传输层可见(serde(skip)),JSON 线格式保持不变。

§参数
  • attachment: 传输层消费的附件描述
  • message: 成功消息
§返回
  • ApiResponse 实例
Source

pub fn with_http_status(self, status: u16) -> Result<Self, BaseError>

覆盖 Action 静态声明的成功 HTTP 状态码。

Source

pub fn with_header( self, name: impl Into<String>, value: impl Into<String>, ) -> Result<Self, BaseError>

追加一个经过最小 RFC 语法校验的响应头。

使用列表而不是 Map,以保留多个 Set-Cookie 等同名响应头。

Source

pub fn response_headers(&self) -> &[(String, String)]

返回 Action 显式追加、由传输层消费的响应头。

响应头不参与 ApiResponse 的 JSON 序列化;此只读视图主要用于 传输适配器、集成测试以及需要检查 Cookie/缓存契约的应用层边界。

Source

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ApiResponse

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ApiResponse

Source§

fn default() -> Self

创建默认响应

默认为成功响应,消息为 “OK”,无数据

Source§

impl JsonSchema for ApiResponse

Source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
Source§

impl Serialize for ApiResponse

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more