使用reqwest
在Axum处理程序中调用外部API的错误处理方法是什么?
使用?
操作符来尝试处理错误,就像在Reqwest文档中一样,会导致编译器抛出错误,因为我的处理程序不再是有效的Axum处理程序。
但是如果不使用?
,即使外部API返回一个错误(例如,接收到一个400
),我也会在我的match
的Ok
分支中结束,导致来自我的API的状态代码总是200
。
如何重构以下代码以正确处理从外部API返回的错误,返回JSON响应,并生成有效的Axum处理程序,以便当用户发出错误请求时,我的API也以正确的状态代码进行响应?
async fn get_weather(
location_query: Query<WeatherQuery>,
) -> Result<Json<serde_json::Value>, Json<serde_json::Value>> {
let location_query = &location_query.location;
let key = std::env::var("WEATHER_STACK_API_KEY").unwrap();
let request_url = format!(
"http://api.weatherstack.com/current?access_key={}&query={}&units=f",
key, location_query
);
let res = reqwest::get(request_url).await;
println!("res: {:?}", res);
match res {
// the response from the reqwest::get() call is always ok, even if the user
// makes a bad request (e.g. "?location=asdf1234")
// since I need to handle that response here, my API is always returning 200
Ok(response) => {
let res_json = response.json::<Weather>().await;
match res_json {
Ok(res) => Ok(Json(serde_json::json!({
"data": res,
"success": true
}))),
Err(_e) => Err(Json(serde_json::json!({
"error": {
"message": "Request to Weather Stack Failed!",
},
"success": false
}))),
}
}
Err(_e) => Err(Json(serde_json::json!({
"error": {
"message": "Internal Server Error. Request failed.",
},
"success": false
}))),
}
}
字符串
1条答案
按热度按时间rqcrx0a61#
你可以将任何可能出错的函数中的大多数错误转换为anyhow Error,然后在你的主处理程序中使用它,在axum仓库中甚至有一个example,这可能是一个有用的考虑。