我在我的Rust应用程序中使用reqwest
(版本0.10.4
)crate进行HTTP调用,但是找不到如何处理可能返回多个可能响应体的API调用的示例,主要是为了错误处理。
例如,API调用可以响应成功的JSON结构,或者格式为错误结构的结构:
{
"errors": ["..."]
}
目前我有这个函数的代码,但似乎无法弄清楚如何确定需要将响应缓冲区反序列化为哪个结构体
,以根据HTTP请求是否成功。
use super::responses::{Error, Response};
use crate::clients::HttpClient;
use crate::errors::HttpError;
use reqwest::header;
pub fn call() -> Result<Response, HttpError> {
let url = format!("{}/auth/userpass/login/{}", addr, user);
let response = HttpClient::new()
.post(&url)
.header(header::ACCEPT, "application/json")
.header(header::CONTENT_TYPE, "application/json")
.json(&serde_json::json!({ "password": pass }))
.send();
match response {
Ok(res) => {
let payload = res.json(); // could be `Error` or `Response` but only parses to `Response`
match payload {
Ok(j) => Ok(j),
Err(e) => Err(HttpError::JsonParse(e)),
}
}
Err(e) => Err(HttpError::RequestFailed(e)),
}
}
我在reqwest
的文档中有遗漏吗?还是这个问题比较普遍?