From 83c9732fb7b99e279c251c7a97d1194c571bb633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flc=E3=82=9B?= Date: Sun, 18 Feb 2024 11:29:51 +0800 Subject: [PATCH] feat(errors): Optimize `Error` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Flcă‚› --- errors/group.go | 9 ++++++++- errors/group_test.go | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/errors/group.go b/errors/group.go index d3955248..1ef537ab 100644 --- a/errors/group.go +++ b/errors/group.go @@ -27,7 +27,14 @@ func (g *Group) Add(errs ...error) *Group { } func (g *Group) Error() string { - return multipleErrors + switch len(g.errors) { + case 0: + return "" + case 1: + return g.errors[0].Error() + default: + return multipleErrors + } } func (g *Group) Errors() []error { diff --git a/errors/group_test.go b/errors/group_test.go index 1642d15f..de56c9ee 100644 --- a/errors/group_test.go +++ b/errors/group_test.go @@ -27,3 +27,25 @@ func TestGroup(t *testing.T) { assert.False(t, g.Has(err3)) assert.Equal(t, err1, g.First()) } + +func TestGroup_Error(t *testing.T) { + g := NewGroup() + assert.Equal(t, "", g.Error()) + + assert.Equal(t, g, g.Add(err1)) + assert.Equal(t, "err1", g.Error()) + + assert.Equal(t, g, g.Add(err2)) + assert.Equal(t, multipleErrors, g.Error()) +} + +func TestGroup_First(t *testing.T) { + g := NewGroup() + assert.Nil(t, g.First()) + + assert.Equal(t, g, g.Add(err1)) + assert.Equal(t, err1, g.First()) + + assert.Equal(t, g, g.Add(err2)) + assert.Equal(t, err1, g.First()) +}