openlark_workflow/common/
api_utils.rs1use openlark_core::error;
8
9pub 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
29pub 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
42pub 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}