Improve error handling for duration parsing
This commit is contained in:
parent
f423da31d2
commit
f852578b11
|
@ -4,6 +4,8 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Duration is a TOML datatype
|
// Duration is a TOML datatype
|
||||||
|
@ -32,7 +34,7 @@ func (d *Duration) UnmarshalTOML(dataInterface interface{}) error {
|
||||||
unit := data[len(data)-1]
|
unit := data[len(data)-1]
|
||||||
value, err := strconv.Atoi(string(data[:len(data)-1]))
|
value, err := strconv.Atoi(string(data[:len(data)-1]))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("unable to parse duration %s: %s", data, err)
|
return errors.Wrapf(err, "unable to parse duration \"%s\"", data)
|
||||||
}
|
}
|
||||||
|
|
||||||
switch unit {
|
switch unit {
|
||||||
|
@ -49,7 +51,7 @@ func (d *Duration) UnmarshalTOML(dataInterface interface{}) error {
|
||||||
case 'y':
|
case 'y':
|
||||||
d.Duration = time.Duration(value) * time.Hour * 24 * 365
|
d.Duration = time.Duration(value) * time.Hour * 24 * 365
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("invalid duration unit: %s", string(unit))
|
return fmt.Errorf("invalid duration unit \"%s\"", string(unit))
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -16,7 +16,7 @@ func TestDuration(t *testing.T) {
|
||||||
duration time.Duration
|
duration time.Duration
|
||||||
}{
|
}{
|
||||||
{"", "invalid duration: \"\"", 0},
|
{"", "invalid duration: \"\"", 0},
|
||||||
{"1x", "invalid duration unit: x", 0},
|
{"1x", "invalid duration unit \"x\"", 0},
|
||||||
{"1s", "", time.Second},
|
{"1s", "", time.Second},
|
||||||
{"73s", "", time.Second * 73},
|
{"73s", "", time.Second * 73},
|
||||||
{"1m", "", time.Minute},
|
{"1m", "", time.Minute},
|
||||||
|
@ -52,6 +52,5 @@ func TestDuration(t *testing.T) {
|
||||||
|
|
||||||
err = d.UnmarshalTOML("am")
|
err = d.UnmarshalTOML("am")
|
||||||
assert.Error(err)
|
assert.Error(err)
|
||||||
assert.Contains(err.Error(), "unable to parse duration")
|
assert.EqualError(err, "unable to parse duration \"am\": strconv.Atoi: parsing \"a\": invalid syntax")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue