feat: improved APIResult error reporting and use tracing
Some checks failed
Test / build (map[name:stable]) (push) Successful in 5m35s
Test / build (map[name:nightly]) (push) Successful in 7m4s
Release Please / Release-plz (push) Failing after 1m2s

This commit is contained in:
Paul Campbell 2024-12-23 09:44:02 +00:00
parent c2b458323f
commit 651bd656c2

View file

@ -1,7 +1,7 @@
//
use kxio::{net::Response, print::Printer};
use crate::{e, s};
use crate::s;
#[derive(Debug)]
pub(crate) struct APIResult<T>
@ -16,23 +16,34 @@ impl<T> APIResult<T>
where
T: for<'a> serde::Deserialize<'a>,
{
pub async fn new(response: kxio::net::Result<Response>, prt: &Printer) -> Self {
pub async fn new(response: kxio::net::Result<Response>, _prt: &Printer) -> Self {
match response {
Ok(response) => {
let text = response.text().await.unwrap_or_default();
let text = if text.is_empty() { s!("null") } else { text };
let result = serde_json::from_str::<T>(&text)
.map_err(|e| e.to_string())
.map_err(|e| {
e!(prt, "{e}: {text}");
e
})
.map_err(kxio::net::Error::from)
.map_err(kxio::Error::from);
Self { text, result }
tracing::trace!(status = %response.status());
match response.status().as_u16() {
200..=299 => {
let text = response.text().await.unwrap_or_default();
let text = if text.is_empty() { s!("null") } else { text };
let result = serde_json::from_str::<T>(&text)
.map_err(|e| e.to_string())
.map_err(|e| {
tracing::error!(error=%e, %text, "APIResult serde_json");
e
})
.map_err(kxio::net::Error::from)
.map_err(kxio::Error::from);
Self { text, result }
}
_ => {
let status = response.status();
let text = response.text().await.unwrap_or_default();
tracing::warn!(%status, %text, "APIResult unsuccessful");
Self::error(kxio::Error::Net(kxio::net::Error::Request(text)))
}
}
}
Err(e) => {
e!(prt, "err: {e:#?}");
tracing::error!(?e, "APIResult err");
Self::error(e.into())
}
}