From 8689a6247ee0c65347bd6bc1669bfacb6d42b5be Mon Sep 17 00:00:00 2001 From: chentong Date: Sat, 3 Aug 2024 11:00:59 +0800 Subject: [PATCH] refactor(core/errorx): use errors.Join simplify error handle (#4289) --- core/errorx/batcherror.go | 18 +++++++----------- core/errorx/batcherror_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/core/errorx/batcherror.go b/core/errorx/batcherror.go index e0fcbb272..4c04e4513 100644 --- a/core/errorx/batcherror.go +++ b/core/errorx/batcherror.go @@ -1,7 +1,7 @@ package errorx import ( - "bytes" + "errors" "sync" ) @@ -52,14 +52,10 @@ func (be *BatchError) NotNil() bool { // Error returns a string that represents inside errors. func (ea errorArray) Error() string { - var buf bytes.Buffer - - for i := range ea { - if i > 0 { - buf.WriteByte('\n') - } - buf.WriteString(ea[i].Error()) - } - - return buf.String() + return errors.Join(ea...).Error() +} + +// Unwrap combine the errors in the errorArray into a single error return +func (ea errorArray) Unwrap() error { + return errors.Join(ea...) } diff --git a/core/errorx/batcherror_test.go b/core/errorx/batcherror_test.go index 3e3453436..bea4d77d2 100644 --- a/core/errorx/batcherror_test.go +++ b/core/errorx/batcherror_test.go @@ -66,3 +66,32 @@ func TestBatchErrorConcurrentAdd(t *testing.T) { assert.Equal(t, count, len(batch.errs)) assert.True(t, batch.NotNil()) } + +func TestBatchError_Unwrap(t *testing.T) { + t.Run("nil", func(t *testing.T) { + var be BatchError + assert.Nil(t, be.Err()) + assert.True(t, errors.Is(be.Err(), nil)) + }) + + t.Run("one error", func(t *testing.T) { + var errFoo = errors.New("foo") + var errBar = errors.New("bar") + var be BatchError + be.Add(errFoo) + assert.True(t, errors.Is(be.Err(), errFoo)) + assert.False(t, errors.Is(be.Err(), errBar)) + }) + + t.Run("two errors", func(t *testing.T) { + var errFoo = errors.New("foo") + var errBar = errors.New("bar") + var errBaz = errors.New("baz") + var be BatchError + be.Add(errFoo) + be.Add(errBar) + assert.True(t, errors.Is(be.Err(), errFoo)) + assert.True(t, errors.Is(be.Err(), errBar)) + assert.False(t, errors.Is(be.Err(), errBaz)) + }) +}