diff options
| author | littleblack111 <littleblack11111@gmail.com> | 2025-09-13 22:37:03 +0800 |
|---|---|---|
| committer | littleblack111 <littleblack11111@gmail.com> | 2025-09-13 22:37:03 +0800 |
| commit | af71458da96fdc7699bed2d04c677a352f5af5fe (patch) | |
| tree | 934d7f94c730a51005899cd7742c21934671497d /src/client/connector/connectors/httpconnector.rs | |
| parent | 3b27ce15cace19804031024f286754aedf86205e (diff) | |
httpconnector: better error handling
Diffstat (limited to 'src/client/connector/connectors/httpconnector.rs')
| -rw-r--r-- | src/client/connector/connectors/httpconnector.rs | 52 |
1 files changed, 36 insertions, 16 deletions
diff --git a/src/client/connector/connectors/httpconnector.rs b/src/client/connector/connectors/httpconnector.rs index 5a5b0df..2a7c0d8 100644 --- a/src/client/connector/connectors/httpconnector.rs +++ b/src/client/connector/connectors/httpconnector.rs @@ -1,39 +1,57 @@ +use reqwest::{Error, StatusCode, Url, blocking::get}; + use crate::connector::*; use std::{thread::sleep, time::Duration}; pub(crate) struct HTTPConnector { prev: String, - url: reqwest::Url, + url: Url, } impl HTTPConnector { pub fn new(url: &str) -> Result<Self, url::ParseError> { Ok(Self { prev: String::new(), - url: reqwest::Url::parse(url)?, + url: Url::parse(url)?, }) } } +pub(crate) enum Err { + Reqwest(Error), + StatusCode(StatusCode), +} + +impl std::fmt::Display for Err { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Err::Reqwest(e) => e.fmt(f), + Err::StatusCode(e) => e.fmt(f), + } + } +} + impl Connection for HTTPConnector { - type Err = reqwest::Error; + type Err = Err; fn update(&self) -> Option<Result<Self::Success, Self::Err>> { - let res = match reqwest::blocking::get(self.url.as_str()) { - Ok(resp) => { - match resp.status() { - reqwest::StatusCode::TOO_MANY_REQUESTS(e) => { - sleep(Duration::from_secs(5)); - return e; - } - status => return Some(Err(status)), + let res = match get(self.url.as_str()) { + Ok(resp) => match resp.status() { + StatusCode::TOO_MANY_REQUESTS => { + sleep(Duration::from_secs(5)); + return self.update(); } - match resp.text() { - Ok(text) => text, - Err(e) => return Some(Err(e)), + status => { + if !status.is_success() { + return Some(Err(Err::StatusCode(status))); + } + match resp.text() { + Ok(text) => text, + Err(e) => return Some(Err(Err::Reqwest(e))), + } } - } - Err(e) => return Some(Err(e)), + }, + Err(e) => return Some(Err(Err::Reqwest(e))), }; if res == self.prev { @@ -42,4 +60,6 @@ impl Connection for HTTPConnector { Some(Ok(res)) } + + // fn ntfy<T>(&self, data: T) {} } |
