下面的代码是我正在编写的用于与Web API交谈的小型库的开头。库的用户将实例化客户端MyClient并通过它访问Web API。在这里,我试图在向API发出请求之前从API获取访问令牌。
在此,get_new_access()我可以发出请求并接收JSON响应。然后,我尝试使用serde将响应转换为Access结构,这就是问题开始的地方。
我创建了一个库特定的错误枚举MyError,该枚举可以表示内可能发生的JSON反序列化和reqwest错误get_new_access()。但是,当我去编译时,我得到了the trait serde::Deserialize<'_> is not implemented for MyError。我的理解是,发生这种情况是因为在遇到上述错误之一的情况下,serde不知道如何将其反序列化为Access结构。当然,我根本不希望它这样做,所以我的问题是我应该怎么做?
我看过各种serde反序列化示例,但它们似乎都假定它们在只能返回serde错误的主函数中运行。如果我#[derive(Deserialize)]在MyError的声明上放上,那么我将得到相同的错误,但它会转移到reqwest::Error和serde_json::Error。
use std::error;
use std::fmt;
extern crate chrono;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use chrono::prelude::*;
use reqwest::Client;
pub struct MyClient {
access: Access,
token_expires: DateTime<Utc>,
}
#[derive(Deserialize, Debug)]
struct Access {
access_token: String,
expires_in: i64,
token_type: String,
}
fn main() {
let sc: MyClient = MyClient::new();
println!("{:?}", &sc.access);
}
impl MyClient {
pub fn new() -> MyClient {
let a: Access = MyClient::get_new_access().expect("Couldn't get Access");
let e: DateTime<Utc> = chrono::Utc::now(); //TODO
MyClient {
access: a,
token_expires: e,
}
}
fn get_new_access() -> Result<Access, MyError> {
let params = ["test"];
let client = Client::new();
let json = client
.post(&[""].concat())
.form(¶ms)
.send()?
.text()
.expect("Couldn't get JSON Response");
println!("{}", &json);
serde_json::from_str(&json)?
//let a = Access {access_token: "Test".to_string(), expires_in: 3600, token_type: "Test".to_string() };
//serde_json::from_str(&json)?
}
}
#[derive(Debug)]
pub enum MyError {
WebRequestError(reqwest::Error),
ParseError(serde_json::Error),
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "eRROR")
}
}
impl error::Error for MyError {
fn description(&self) -> &str {
"API internal error"
}
fn cause(&self) -> Option<&error::Error> {
// Generic error, underlying cause isn't tracked.
None
}
}
impl From<serde_json::Error> for MyError {
fn from(e: serde_json::Error) -> Self {
MyError::ParseError(e)
}
}
impl From<reqwest::Error> for MyError {
fn from(e: reqwest::Error) -> Self {
MyError::WebRequestError(e)
}
}
Run Code Online (Sandbox Code Playgroud)
游乐场链接在这里。
您的第一个问题是您fn get_new_access() -> Result<Access, MyError>期望得到一个Result。但是在这里:
//...
serde_json::from_str(&json)?
}
Run Code Online (Sandbox Code Playgroud)
由于使用了?(try宏),因此您尝试返回Result的未包装值是的子类型 serde::Deserialize<'_>。编译器警告您这Deserialize不是Result。您应该做的只是返回结果而不解包:
//...
serde_json::from_str(&json)
}
Run Code Online (Sandbox Code Playgroud)
要么
//...
let access = serde_json::from_str(&json)?; // gets access or propagates error
Ok(access) //if no error return access in a Result
}
Run Code Online (Sandbox Code Playgroud)
然后,您将遇到第二个问题,因为您的函数希望MyError在此调用Result返回的同时进行。幸运的是,该函数具有将实际错误类型映射到您的自定义错误类型的功能。serde_json::Errorserde_json::from_str(&json)Resultmap_err
此代码将解决您的问题:
//...
serde_json::from_str(&json).map_err(MyError::ParseError)
}
Run Code Online (Sandbox Code Playgroud)
对于评论中的请求:
例如,如果我将Web请求行更改为
let json = client.post("").form(¶ms).send().map_err(MyError::WebRequestError)?.text()?;,那是更好的做法吗?
是的,但是由于text()返回a,因此Result您也需要映射它的错误MyError。由于send和text具有相同的错误type(reqwest::Error),您可以将结果与and_then:
let json = client
.post(&[""].concat())
.form(¶ms)
.send()
.and_then(Response::text) //use reqwest::Response;
.map_err(MyError::WebRequestError)?;
Run Code Online (Sandbox Code Playgroud)