Skip to content

Commit 8a13b04

Browse files
committed
Nicer error message for plain numeric duration
Inspired by #6
1 parent edfa493 commit 8a13b04

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/duration.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,16 @@ impl fmt::Display for Error {
4646
match self {
4747
Error::InvalidCharacter(offset) => write!(f, "invalid character at {}", offset),
4848
Error::NumberExpected(offset) => write!(f, "expected number at {}", offset),
49+
Error::UnknownUnit(start, end) if start == end => write!(f,
50+
"time unit needed at {}, for example 100ms or 100sec",
51+
start+1,
52+
),
4953
Error::UnknownUnit(start, end) => write!(
5054
f,
5155
"unknown time unit at {}-{}, \
52-
see documentation of `parse_duration` for the list of supported time units",
53-
start, end
56+
supported units: ns, us, ms, sec, min, hours, days, weeks, \
57+
months, years (and few variations)",
58+
start+1, end
5459
),
5560
Error::NumberOverflow => write!(f, "number is too large"),
5661
Error::Empty => write!(f, "value was empty"),
@@ -410,4 +415,16 @@ mod test {
410415
assert_eq!(parse_duration("10000000000000y"),
411416
Err(Error::NumberOverflow));
412417
}
418+
419+
#[test]
420+
fn test_nice_error_message() {
421+
assert_eq!(parse_duration("10").unwrap_err().to_string(),
422+
"time unit needed at 3, for example 100ms or 100sec");
423+
assert_eq!(parse_duration("10 months 1").unwrap_err().to_string(),
424+
"time unit needed at 12, for example 100ms or 100sec");
425+
assert_eq!(parse_duration("10nights").unwrap_err().to_string(),
426+
"unknown time unit at 3-8, supported units: \
427+
ns, us, ms, sec, min, hours, days, weeks, months, \
428+
years (and few variations)");
429+
}
413430
}

0 commit comments

Comments
 (0)