Skip to content

Commit 6065ef1

Browse files
committed
Refactor error handling and remove unused typing module
- Removed the `typing` module and its associated types and functions. - Replaced custom error handling with `anyhow` for better error management across various modules. - Updated function signatures in `calendar`, `iccard`, `jwcas`, `lab`, `jwqywx`, and `sso` implementations to return `anyhow::Result` instead of custom error types. - Adjusted error handling in `recursion` to use `anyhow` for improved clarity and consistency. - Ensured all relevant functions propagate errors correctly using the new error handling approach.
1 parent 9b64c69 commit 6065ef1

14 files changed

Lines changed: 269 additions & 375 deletions

File tree

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ uuid = { version = "1", features = ["v4", "v3"], optional = true }
2828
chrono = { version = "0.4", optional = true }
2929
icalendar = { version = "0.17.5", optional = true }
3030
const_format = "0.2.34"
31+
anyhow = "1"
3132

3233

3334
[features]

src/base/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
pub mod app;
22
pub mod client;
3-
pub mod typing;

src/base/typing.rs

Lines changed: 0 additions & 9 deletions
This file was deleted.

src/extension/calendar.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::{
77
};
88
use uuid::Uuid;
99

10-
use crate::base::typing::{other_error, TorErr};
10+
use anyhow::{Result, bail};
1111

1212
pub static EVENT_PROP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
1313
let mut map: HashMap<&str, &str> = HashMap::new();
@@ -207,28 +207,28 @@ pub trait ApplicationCalendarExt {
207207
firstweekdate: String,
208208
schedule: Schedule,
209209
reminder: Option<i32>,
210-
) -> TorErr<Calendar>;
210+
) -> Result<Calendar>;
211211
fn generate_icalendar(
212212
&self,
213213
firstweekdate: String,
214214
schedule: Schedule,
215215
reminder: Option<i32>,
216-
) -> impl Future<Output = TorErr<Calendar>>;
216+
) -> impl Future<Output = Result<Calendar>>;
217217
}
218218

219219
pub trait CalendarParser {
220220
/// The Matrix's column is indexed 0~6
221221
///
222222
/// Each Vec<String> is in order.
223223
224-
fn get_classinfo_week_matrix(&self) -> impl Future<Output = TorErr<Vec<Vec<RawCourse>>>>;
224+
fn get_classinfo_week_matrix(&self) -> impl Future<Output = Result<Vec<Vec<RawCourse>>>>;
225225
}
226226

227227
pub trait TermCalendarParser: CalendarParser {
228228
fn get_term_classinfo_week_matrix(
229229
&self,
230230
term: String,
231-
) -> impl Future<Output = TorErr<Vec<Vec<RawCourse>>>>;
231+
) -> impl Future<Output = Result<Vec<Vec<RawCourse>>>>;
232232
}
233233

234234
impl<P: CalendarParser> ApplicationCalendarExt for P {
@@ -238,7 +238,7 @@ impl<P: CalendarParser> ApplicationCalendarExt for P {
238238
firstweekdate: String,
239239
schedule: Schedule,
240240
reminder: Option<i32>,
241-
) -> TorErr<Calendar> {
241+
) -> Result<Calendar> {
242242
let mut calendar = Calendar::new();
243243
calendar.timezone("Asia/Shanghai").name("课程表");
244244
let mut classlist = classlist;
@@ -332,7 +332,7 @@ impl<P: CalendarParser> ApplicationCalendarExt for P {
332332
firstmonday: String,
333333
schedule: Schedule,
334334
reminder: Option<i32>,
335-
) -> TorErr<Calendar> {
335+
) -> Result<Calendar> {
336336
let classlist = self.get_classinfo_week_matrix().await?;
337337

338338
self.generate_icalendar_from_classlist(
@@ -344,15 +344,15 @@ impl<P: CalendarParser> ApplicationCalendarExt for P {
344344
}
345345
}
346346

347-
pub fn parse_week_matrix(row_matrix: Vec<Vec<RawCourse>>) -> TorErr<Vec<ParsedCourse>> {
347+
pub fn parse_week_matrix(row_matrix: Vec<Vec<RawCourse>>) -> Result<Vec<ParsedCourse>> {
348348
let mut column_matrix: Vec<Vec<RawCourse>> = vec![];
349349
for i in 0..7 {
350350
let mut column: Vec<RawCourse> = vec![];
351351
for v in row_matrix.iter() {
352352
if let Some(value) = v.get(i) {
353353
column.push(value.clone())
354354
} else {
355-
return Err(other_error("Parse Classinfo error"));
355+
bail!("Parse Classinfo error");
356356
}
357357
}
358358
column_matrix.push(column);

src/impls/apps/iccard/iccard.rs

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,14 @@ use std::fmt::Display;
33
use tokio::join;
44

55
use crate::{
6-
base::{
7-
app::Application,
8-
client::Client,
9-
typing::{other_error, TorErr},
10-
},
6+
base::{app::Application, client::Client},
117
impls::apps::iccard::{
128
iccard_constants::PRESET_DORMBUILDINGS,
139
iccard_type::{DormArea, DormBuilding, DormBuildingsData, DormRoomElectricityBillData},
1410
},
1511
internals::fields::DEFAULT_HEADERS,
1612
};
13+
use anyhow::Result;
1714

1815
pub struct ICCardApplication<C, S> {
1916
pub client: C,
@@ -38,7 +35,7 @@ impl<C: Client + Clone, S: Display> ICCardApplication<C, S> {
3835
area: DormArea<impl Into<String>>,
3936
building: DormBuilding,
4037
room: impl Into<String>,
41-
) -> TorErr<DormRoomElectricityBillData> {
38+
) -> Result<DormRoomElectricityBillData> {
4239
let url = self.endpoint("wechat/callinterface/queryElecRoomInfo.html");
4340
let areaname = area.name.into();
4441
let areaid = area.id.into();
@@ -69,15 +66,14 @@ impl<C: Client + Clone, S: Display> ICCardApplication<C, S> {
6966
}).to_string(),
7067
}))
7168
.send()
72-
.await
73-
.map_err(other_error)?;
74-
Ok(response.json().await.map_err(other_error)?)
69+
.await?;
70+
Ok(response.json().await?)
7571
}
7672

7773
pub async fn list_buildings(
7874
&self,
7975
area: DormArea<impl Into<String>>,
80-
) -> TorErr<DormBuildingsData> {
76+
) -> Result<DormBuildingsData> {
8177
let url = self.endpoint("wechat/callinterface/queryElecBuilding.html");
8278
let id = area.id.into();
8379
let name = area.name.into();
@@ -97,12 +93,11 @@ impl<C: Client + Clone, S: Display> ICCardApplication<C, S> {
9793
"account": self.client.account().user,
9894
}))
9995
.send()
100-
.await
101-
.map_err(other_error)?;
102-
Ok(response.json().await.map_err(other_error)?)
96+
.await?;
97+
Ok(response.json().await?)
10398
}
10499

105-
pub async fn list_all_preset_buildings(&self) -> TorErr<Vec<DormBuildingsData>> {
100+
pub async fn list_all_preset_buildings(&self) -> Result<Vec<DormBuildingsData>> {
106101
let task = |index: usize| async move {
107102
let area: DormArea<&'static str> = PRESET_DORMBUILDINGS[index].clone();
108103

src/impls/apps/sso/jwcas.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use scraper::{ElementRef, Html, Selector};
55

66
use crate::base::app::Application;
77
use crate::base::client::Client;
8-
use crate::base::typing::{other_error, EmptyOrErr, TorErr};
98
use crate::impls::services::sso_redirect::SSORedirect;
109
use crate::internals::recursion::recursion_redirect_handle;
10+
use anyhow::{bail, Result};
1111

1212
use super::jwcas_type::GradeData;
1313

@@ -28,42 +28,39 @@ impl<C: Client + Clone> Application<C> for JwcasApplication<C> {
2828

2929
impl<C: Client + Clone + Send> JwcasApplication<C> {
3030
/// will call login after [`Self::from_client`]
31-
pub async fn from_client_login(client: C) -> TorErr<Self> {
31+
pub async fn from_client_login(client: C) -> Result<Self> {
3232
let app = Self::from_client(client).await;
3333
app.login().await?;
3434
Ok(app)
3535
}
3636

3737
/// Visit this Url will login in too.
38-
pub async fn login(&self) -> EmptyOrErr {
38+
pub async fn login(&self) -> Result<()> {
3939
let api = format!("{}/web_cas/web_cas_login_jwgl.aspx", self.root);
40-
recursion_redirect_handle(self.client.clone(), &api)
41-
.await
42-
.map_err(other_error)?;
40+
recursion_redirect_handle(self.client.clone(), &api).await?;
4341
Ok(())
4442
}
4543

46-
pub async fn get_classlist_html(&self) -> TorErr<String> {
44+
pub async fn get_classlist_html(&self) -> Result<String> {
4745
self.get_html("/web_jxrw/cx_kb_xsgrkb.aspx").await
4846
}
4947

50-
pub async fn get_gradelist_html(&self) -> TorErr<String> {
48+
pub async fn get_gradelist_html(&self) -> Result<String> {
5149
self.get_html("/web_cjgl/cx_cj_jxjhcj_xh.aspx").await
5250
}
5351

54-
pub async fn get_html(&self, service: impl Display) -> TorErr<String> {
52+
pub async fn get_html(&self, service: impl Display) -> Result<String> {
5553
let api = format!("{}{}", self.root, service);
5654

5755
if let Ok(response) = self.client.reqwest_client().get(api).send().await {
5856
if response.status() == StatusCode::OK {
5957
return Ok(response.text().await.unwrap());
6058
}
6159
}
62-
63-
Err(other_error(format!("Get {service} failed")))
60+
bail!("Get {service} failed");
6461
}
6562

66-
pub async fn get_gradeinfo_vec(&self) -> TorErr<Vec<GradeData>> {
63+
pub async fn get_gradeinfo_vec(&self) -> Result<Vec<GradeData>> {
6764
let text = self.get_gradelist_html().await?;
6865
let tb_up = Selector::parse(r#"table[id="GVkbk"]"#).unwrap();
6966
let selector = Selector::parse(r#"tr[class="dg1-item"]"#).unwrap();
@@ -97,15 +94,15 @@ fn extract_string(element: Option<&ElementRef>) -> String {
9794
pub mod calendar {
9895
use std::collections::HashMap;
9996

97+
use anyhow::{Context, Result};
10098
use scraper::{Html, Selector};
10199

102100
use crate::base::client::Client;
103-
use crate::base::typing::{other_error, TorErr};
104101
use crate::extension::calendar::{CalendarParser, RawCourse};
105102

106103
use super::JwcasApplication;
107104
impl<C: Client + Clone + Send> CalendarParser for JwcasApplication<C> {
108-
async fn get_classinfo_week_matrix(&self) -> TorErr<Vec<Vec<RawCourse>>> {
105+
async fn get_classinfo_week_matrix(&self) -> Result<Vec<Vec<RawCourse>>> {
109106
let text = self.get_classlist_html().await?;
110107
let doc = Html::parse_document(&text);
111108

@@ -121,7 +118,7 @@ pub mod calendar {
121118
let mut teachers = HashMap::new();
122119
doc.select(&tb_up_rowseletor)
123120
.next()
124-
.ok_or(other_error("Select Teacher Failed"))?
121+
.context("Select Teacher Failed")?
125122
.select(&tb_dg1_itemseletor)
126123
.for_each(|e| {
127124
let items: Vec<String> = e
@@ -143,7 +140,7 @@ pub mod calendar {
143140
Ok(doc
144141
.select(&tb_dn_seletor)
145142
.next()
146-
.ok_or(other_error("Select Course Failed"))?
143+
.context("Select Course Failed")?
147144
.select(&tb_dg1_itemseletor)
148145
.map(|e| {
149146
let mut items: Vec<String> = e

src/impls/apps/sso/lab.rs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
use std::collections::HashMap;
22

33
use crate::{
4-
base::{
5-
app::Application,
6-
client::Client,
7-
typing::{other_error, EmptyOrErr, TorErr},
8-
},
4+
base::{app::Application, client::Client},
95
impls::login::sso::SSOUniversalLogin,
106
internals::fields::DEFAULT_HEADERS,
117
};
8+
use anyhow::Result;
129

1310
static LABAPP_ROOT: &'static str = "https://sysaqgl.cczu.edu.cn";
1411

@@ -24,15 +21,15 @@ impl<C: Client> Application<C> for LabApplication<C> {
2421

2522
impl<C: Client + Clone + Send + Sync> LabApplication<C> {
2623
/// Support LAN/WAN
27-
pub async fn exam_login(&self) -> EmptyOrErr {
24+
pub async fn exam_login(&self) -> Result<()> {
2825
self.client
2926
.sso_service_login(format!("{LABAPP_ROOT}/labexam/examIDSLogin.php"))
3027
.await?;
3128

3229
Ok(())
3330
}
3431

35-
pub async fn exam_increase_thirty_secs(&self) -> TorErr<LabExamStudyInfo> {
32+
pub async fn exam_increase_thirty_secs(&self) -> Result<LabExamStudyInfo> {
3633
let api = format!("{LABAPP_ROOT}/labexam/exam_xuexi_online.php");
3734
let mut params = HashMap::new();
3835
params.insert("cmd", "xuexi_online");
@@ -44,11 +41,9 @@ impl<C: Client + Clone + Send + Sync> LabApplication<C> {
4441
.headers(DEFAULT_HEADERS.clone())
4542
.form(&params)
4643
.send()
47-
.await
48-
.map_err(other_error)?
44+
.await?
4945
.json()
50-
.await
51-
.map_err(other_error)?)
46+
.await?)
5247
}
5348
}
5449

0 commit comments

Comments
 (0)