From f852578b11b6572598b447d62419a9cba9825909 Mon Sep 17 00:00:00 2001 From: Julian Kornberger Date: Tue, 2 Jan 2018 09:50:00 +0100 Subject: [PATCH] Improve error handling for duration parsing --- runtime/duration.go | 6 ++++-- runtime/duration_test.go | 5 ++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/runtime/duration.go b/runtime/duration.go index ef9b557..255d4ca 100644 --- a/runtime/duration.go +++ b/runtime/duration.go @@ -4,6 +4,8 @@ import ( "fmt" "strconv" "time" + + "github.com/pkg/errors" ) // Duration is a TOML datatype @@ -32,7 +34,7 @@ func (d *Duration) UnmarshalTOML(dataInterface interface{}) error { unit := data[len(data)-1] value, err := strconv.Atoi(string(data[:len(data)-1])) 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 { @@ -49,7 +51,7 @@ func (d *Duration) UnmarshalTOML(dataInterface interface{}) error { case 'y': d.Duration = time.Duration(value) * time.Hour * 24 * 365 default: - return fmt.Errorf("invalid duration unit: %s", string(unit)) + return fmt.Errorf("invalid duration unit \"%s\"", string(unit)) } return nil diff --git a/runtime/duration_test.go b/runtime/duration_test.go index 340fe47..d17f475 100644 --- a/runtime/duration_test.go +++ b/runtime/duration_test.go @@ -16,7 +16,7 @@ func TestDuration(t *testing.T) { duration time.Duration }{ {"", "invalid duration: \"\"", 0}, - {"1x", "invalid duration unit: x", 0}, + {"1x", "invalid duration unit \"x\"", 0}, {"1s", "", time.Second}, {"73s", "", time.Second * 73}, {"1m", "", time.Minute}, @@ -52,6 +52,5 @@ func TestDuration(t *testing.T) { err = d.UnmarshalTOML("am") 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") }