From b40b53a7620fd801392fd8323a149f72098b2764 Mon Sep 17 00:00:00 2001 From: crozzy Date: Mon, 9 Oct 2023 09:18:42 -0700 Subject: [PATCH] Wrap parsing error to allow caller to discern why things failed It's hard to reason with errors when `strconv.ParseUint` fails as the returned error is untyped. This change wraps the parsing error. Signed-off-by: crozzy --- version.go | 6 +++--- version_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/version.go b/version.go index 304edc3..1cb4e21 100644 --- a/version.go +++ b/version.go @@ -156,13 +156,13 @@ func NewVersion(v string) (*Version, error) { var err error sv.major, err = strconv.ParseUint(m[1], 10, 64) if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) + return nil, fmt.Errorf("error parsing version segment: %w", err) } if m[2] != "" { sv.minor, err = strconv.ParseUint(m[2], 10, 64) if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) + return nil, fmt.Errorf("error parsing version segment: %w", err) } } else { sv.minor = 0 @@ -171,7 +171,7 @@ func NewVersion(v string) (*Version, error) { if m[3] != "" { sv.patch, err = strconv.ParseUint(m[3], 10, 64) if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) + return nil, fmt.Errorf("error parsing version segment: %w", err) } } else { sv.patch = 0 diff --git a/version_test.go b/version_test.go index 2899598..309540b 100644 --- a/version_test.go +++ b/version_test.go @@ -3,7 +3,9 @@ package semver import ( "database/sql" "encoding/json" + "errors" "fmt" + "strconv" "testing" ) @@ -193,6 +195,34 @@ func TestOriginal(t *testing.T) { } } +func TestErrors(t *testing.T) { + tests := map[string]error{ + "1.3.2023080721291691443750": strconv.ErrRange, + "1.2.3.4.5": ErrInvalidSemVer, + "": ErrInvalidSemVer, + "1.2.0+invalid_metadata": ErrInvalidSemVer, + } + for v, e := range tests { + _, err := NewVersion(v) + if !errors.Is(err, e) { + t.Errorf("Expecting error: %s but got: %s, version %s", e, err, v) + } + } + + strictTests := map[string]error{ + "1.3.2023080721291691443750": strconv.ErrRange, + "1.2.3.4.5": ErrInvalidCharacters, + "": ErrEmptyString, + "1.2.0+invalid$metadata": ErrInvalidMetadata, + } + for v, e := range strictTests { + _, err := StrictNewVersion(v) + if !errors.Is(err, e) { + t.Errorf("Expecting error: %s but got: %s, version: %s", e, err, v) + } + } +} + func TestParts(t *testing.T) { v, err := NewVersion("1.2.3-beta.1+build.123") if err != nil {