Skip to content

Commit e3005da

Browse files
committed
Add error handling
1 parent 1831d8f commit e3005da

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

src/rtc.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ use rtcc::{DateTimeAccess, Datelike, Hours, NaiveDate, NaiveDateTime, NaiveTime,
1818
pub enum Error {
1919
/// Invalid input error
2020
InvalidInputData,
21+
/// Invalid register data, failed to convert to rtcc Type
22+
InvalidRtcData,
2123
}
2224

2325
/// Real Time Clock peripheral
@@ -178,12 +180,10 @@ impl DateTimeAccess for Rtc {
178180
let minutes = self.minutes()?;
179181
let hours = hours_to_u8(self.hours()?)?;
180182

181-
Ok(
182-
NaiveDate::from_ymd_opt(year.into(), month.into(), day.into())
183-
.unwrap()
184-
.and_hms_opt(hours.into(), minutes.into(), seconds.into())
185-
.unwrap(),
186-
)
183+
NaiveDate::from_ymd_opt(year.into(), month.into(), day.into())
184+
.ok_or(Error::InvalidRtcData)?
185+
.and_hms_opt(hours.into(), minutes.into(), seconds.into())
186+
.ok_or(Error::InvalidRtcData)
187187
}
188188
}
189189

@@ -332,7 +332,8 @@ impl Rtcc for Rtc {
332332
let minutes = self.minutes()?;
333333
let hours = hours_to_u8(self.hours()?)?;
334334

335-
Ok(NaiveTime::from_hms_opt(hours.into(), minutes.into(), seconds.into()).unwrap())
335+
NaiveTime::from_hms_opt(hours.into(), minutes.into(), seconds.into())
336+
.ok_or(Error::InvalidRtcData)
336337
}
337338

338339
fn weekday(&mut self) -> Result<u8, Self::Error> {
@@ -365,7 +366,7 @@ impl Rtcc for Rtc {
365366
let month = self.month()?;
366367
let year = self.year()?;
367368

368-
Ok(NaiveDate::from_ymd_opt(year.into(), month.into(), day.into()).unwrap())
369+
NaiveDate::from_ymd_opt(year.into(), month.into(), day.into()).ok_or(Error::InvalidRtcData)
369370
}
370371
}
371372

@@ -379,13 +380,13 @@ fn bcd2_encode(word: u32) -> Result<(u8, u8), Error> {
379380
let l = match (word / 10).try_into() {
380381
Ok(v) => v,
381382
Err(_) => {
382-
return Err(Error::InvalidInputData);
383+
return Err(Error::InvalidRtcData);
383384
}
384385
};
385386
let r = match (word % 10).try_into() {
386387
Ok(v) => v,
387388
Err(_) => {
388-
return Err(Error::InvalidInputData);
389+
return Err(Error::InvalidRtcData);
389390
}
390391
};
391392

0 commit comments

Comments
 (0)