Skip to main content

openlark_workflow/common/
api_utils.rs

1/// API通用工具函数(re-export core canonical + 本域 error 构造器)。
2///
3/// `serialize_params` 已下沉到
4/// `openlark_core::api`(#330),本模块 re-export canonical copy;保留 workflow 域专用的
5/// 标准 error 构造器(`missing_response_data_error` / `request_serialization_error`),
6/// 多处审批任务叶子直接复用其错误形状。
7use openlark_core::error;
8
9// canonical HTTP 管道 helper(#330 下沉到 core)
10pub use openlark_core::api::serialize_params;
11
12const ERROR_COMPONENT: &str = "openlark-workflow";
13
14fn attach_standard_error_context(
15    err: openlark_core::error::CoreError,
16    operation: &str,
17    resource: &str,
18    request_id: Option<String>,
19) -> openlark_core::error::CoreError {
20    err.with_operation(operation, ERROR_COMPONENT)
21        .map_context(|ctx| {
22            ctx.add_context("resource", resource);
23            if let Some(request_id) = request_id.filter(|value| !value.trim().is_empty()) {
24                ctx.set_request_id(request_id);
25            }
26        })
27}
28
29/// 创建“响应 data 为空”的标准错误。
30pub fn missing_response_data_error(
31    resource: &str,
32    request_id: Option<String>,
33) -> openlark_core::error::CoreError {
34    attach_standard_error_context(
35        error::validation_error("response.data", "服务器没有返回有效的数据"),
36        "extract_response_data",
37        resource,
38        request_id,
39    )
40}
41
42/// 创建“请求参数序列化失败”的标准错误。
43pub fn request_serialization_error(
44    resource: &str,
45    source: impl std::fmt::Display,
46) -> openlark_core::error::CoreError {
47    attach_standard_error_context(
48        error::validation_error("request.params", format!("无法序列化请求参数: {source}")),
49        "serialize_params",
50        resource,
51        None,
52    )
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58    use openlark_core::error::ErrorTrait;
59
60    #[test]
61    fn missing_response_data_error_attaches_context() {
62        let err = missing_response_data_error("审批任务查询", Some("req-wf-456".to_string()));
63        assert_eq!(err.context().operation(), Some("extract_response_data"));
64        assert_eq!(err.context().component(), Some(ERROR_COMPONENT));
65        assert_eq!(err.context().get_context("resource"), Some("审批任务查询"));
66        assert_eq!(err.context().request_id(), Some("req-wf-456"));
67    }
68
69    #[test]
70    fn request_serialization_error_attaches_context() {
71        let err = request_serialization_error("退回审批任务", "boom");
72        assert_eq!(err.context().operation(), Some("serialize_params"));
73        assert_eq!(err.context().get_context("resource"), Some("退回审批任务"));
74    }
75}