Skip to content

Commit cc8e0fd

Browse files
committed
added super error for pg_interval parse error to add std::error:Error trait support
1 parent 9ba0311 commit cc8e0fd

File tree

3 files changed

+55
-2
lines changed

3 files changed

+55
-2
lines changed

Cargo.lock

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,6 @@ pg_interval = "0.4.2"
1313
postgres-types = "0.2.6"
1414
serde = { version = "1.0.197", features = ["derive"] }
1515
serde_json = "1.0.115"
16+
17+
[dev-dependencies]
18+
anyhow = "1.0.81"

src/lib.rs

+45-2
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,49 @@ use postgres_types::private::BytesMut;
99
use serde::{Deserialize, Serialize};
1010
use serde::ser::{SerializeStruct};
1111
use std::convert::TryInto;
12+
use std::fmt::{Display, Formatter};
13+
14+
#[derive(Debug, PartialEq, Eq)]
15+
pub struct ParseError {
16+
pg: pg_interval::ParseError,
17+
}
18+
19+
impl From<pg_interval::ParseError> for ParseError {
20+
fn from(pg: pg_interval::ParseError) -> ParseError {
21+
ParseError {
22+
pg
23+
}
24+
}
25+
}
26+
27+
impl Into<pg_interval::ParseError> for ParseError {
28+
fn into(self) -> pg_interval::ParseError {
29+
self.pg
30+
}
31+
}
32+
33+
impl Display for ParseError {
34+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
35+
match &self.pg {
36+
pg_interval::ParseError::InvalidInterval(s) => write!(f, "{}", s),
37+
pg_interval::ParseError::InvalidTime(s) => write!(f, "{}", s),
38+
pg_interval::ParseError::InvalidYearMonth(s) => write!(f, "{}", s),
39+
pg_interval::ParseError::ParseIntErr(s) => write!(f, "{}", s),
40+
pg_interval::ParseError::ParseFloatErr(s) => write!(f, "{}", s),
41+
}
42+
}
43+
}
44+
45+
impl Error for ParseError {
46+
}
1247

1348
#[derive(Debug)]
1449
pub struct Interval {
1550
pg: pg_interval::Interval,
1651
}
1752

1853
impl Interval {
19-
pub fn new(interval: &str) -> Result<Interval, pg_interval::ParseError> {
54+
pub fn new(interval: &str) -> Result<Interval, ParseError> {
2055
Ok(Interval {
2156
pg: pg_interval::Interval::from_postgres(&interval)?,
2257
})
@@ -36,7 +71,7 @@ impl Interval {
3671
}
3772

3873
impl FromStr for Interval {
39-
type Err = pg_interval::ParseError;
74+
type Err = ParseError;
4075

4176
fn from_str(s: &str) -> Result<Self, Self::Err> {
4277
Interval::new(s)
@@ -202,4 +237,12 @@ mod tests {
202237
assert_eq!(deserialized.pg.days, 2);
203238
assert_eq!(deserialized.pg.microseconds, 3);
204239
}
240+
241+
#[test]
242+
fn test_anyhow_error_propagation() {
243+
let interval = (|| -> anyhow::Result<Interval> {
244+
Ok(Interval::new("1 monthss")?)
245+
})();
246+
assert_eq!(interval.err().unwrap().to_string(), "Unknown or duplicate deliminator \"monthss\"");
247+
}
205248
}

0 commit comments

Comments
 (0)