【发布时间】:2019-05-22 16:24:20
【问题描述】:
下面的代码是我为与 Web API 对话而编写的一个小型库的开始。该库的用户将实例化一个客户端 MyClient 并通过它访问 Web API。在这里,我尝试在向 API 发出请求之前从 API 获取访问令牌。
在get_new_access() 中,我可以发出请求并接收 JSON 响应。然后我尝试使用 serde 将响应转换为 Access 结构,这就是问题的开始。
我创建了一个库特定的错误枚举MyError,它可以表示get_new_access() 中可能发生的 JSON 反序列化和 reqwest 错误。但是,当我去编译时,我得到了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)
}
}
游乐场链接here。
【问题讨论】:
-
请发送正确的minimal reproducible example。该代码中缺少语法错误和其他部分,这使我们无法重现该问题。特别是,您提到了
MyError类型,并在您未提供的main函数中使用了MyClient。考虑制作一些在Rust Playground 中运行并显示相同问题的东西。 rust tag info 中也有 Rust 特定的提示。 -
更新了代码以重现错误和游乐场链接
-
minimal reproducible example 中的所有单词都很重要。 Minimal 是第一个。