Expand description
微信小程序错误处理模块
该模块定义了与微信小程序 API 交互过程中可能遇到的所有错误类型, 包括微信官方错误码映射和第三方库错误转换。
§错误类型
模块包含两种主要的错误类型:
§错误处理示例
use wechat_minapp::error::{Error, ErrorCode};
// 处理微信 API 返回的错误
fn handle_wechat_error(errcode: i32, errmsg: String) -> Result<(), Error> {
if let Some(code) = ErrorCode::from_repr(errcode) {
return Err(Error::from((code, errmsg)));
}
Ok(())
}
// 处理网络错误
async fn make_api_request() -> Result<(), Error> {
let client = reqwest::Client::new();
let response = client.get("https://api.weixin.qq.com/some/endpoint")
.send()
.await?; // 自动转换为 Error::Reqwest
Ok(())
}§错误转换
模块自动实现了从常见第三方库错误到 Error 的转换:
reqwest::Error→Error::Reqwestserde_json::Error→Error::SerdeJsonbase64::DecodeError→Error::Base64Decodeaes::cipher::InvalidLength→Error::AesInvalidLength
这使得错误处理更加方便,可以使用 ? 操作符自动转换。