wx_rust_common/error/
wx_error.rs1use serde::{Deserialize, Serialize};
6
7use crate::enums::WxType;
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct WxError {
20 #[serde(rename = "errcode", default)]
22 pub error_code: i32,
23
24 #[serde(rename = "errmsg")]
26 pub error_msg: Option<String>,
27
28 pub error_msg_en: Option<String>,
30
31 #[serde(skip)]
33 pub json: Option<String>,
34}
35
36impl WxError {
37 pub fn new(error_code: i32, error_msg: impl Into<String>) -> Self {
43 Self {
44 error_code,
45 error_msg: Some(error_msg.into()),
46 error_msg_en: None,
47 json: None,
48 }
49 }
50
51 pub fn from_json(json: &str) -> Self {
59 Self::from_json_with_type(json, None)
60 }
61
62 pub fn from_json_with_type(json: &str, wx_type: Option<WxType>) -> Self {
71 let mut err = match serde_json::from_str::<WxError>(json) {
72 Ok(e) => e,
73 Err(_) => WxError {
74 error_code: -99,
75 error_msg: Some(format!("JSON 解析失败,原始报文:{json}")),
76 error_msg_en: None,
77 json: Some(json.to_string()),
78 },
79 };
80 err.json = Some(json.to_string());
81
82 if err.error_code == 0 || wx_type.is_none() {
83 return err;
84 }
85 if let Some(msg) = &err.error_msg {
86 if !msg.is_empty() {
87 err.error_msg_en = Some(msg.clone());
88 }
89 }
90
91 if let Some(t) = wx_type {
92 let translated = super::translate_error_msg(t, err.error_code);
93 if let Some(msg) = translated {
94 err.error_msg = Some(msg.to_string());
95 }
96 }
97 err
98 }
99}
100
101impl std::fmt::Display for WxError {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 if let Some(json) = &self.json {
104 write!(
105 f,
106 "错误代码:{}, 错误信息:{},微信原始报文:{}",
107 self.error_code,
108 self.error_msg.as_deref().unwrap_or(""),
109 json
110 )
111 } else {
112 write!(
113 f,
114 "错误代码:{}, 错误信息:{}",
115 self.error_code,
116 self.error_msg.as_deref().unwrap_or("")
117 )
118 }
119 }
120}