error collector (mostly for migrations)

This commit is contained in:
Pavel 2019-10-30 17:02:11 +03:00
parent f2b79fad5c
commit 06cab9921d
2 changed files with 78 additions and 0 deletions

38
core/error_collector.go Normal file
View File

@ -0,0 +1,38 @@
package core
import (
"github.com/pkg/errors"
)
// ErrorCollector can be used to group several error calls into one call.
// It is mostly useful in GORM migrations, where you should return only one errors, but several can occur.
// Error messages are composed into one message. For example:
// err := core.ErrorCollector(
// errors.New("first"),
// errors.New("second")
// )
//
// // Will output `first < second`
// fmt.Println(err.Error())
// Example with GORM migration, returns one migration error with all error messages:
// return core.ErrorCollector(
// db.CreateTable(models.Account{}, models.Connection{}).Error,
// db.Table("account").AddUniqueIndex("account_key", "channel").Error,
// )
func ErrorCollector(errorsList ...error) error {
var errorMsg string
for _, errItem := range errorsList {
if errItem == nil {
continue
}
errorMsg += "< " + errItem.Error() + " "
}
if errorMsg != "" {
return errors.New(errorMsg[2 : len(errorMsg)-1])
}
return nil
}

View File

@ -0,0 +1,40 @@
package core
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestErrorCollector_NoError(t *testing.T) {
err := ErrorCollector(nil, nil, nil)
assert.NoError(t, err)
assert.Nil(t, err)
}
func TestErrorCollector_SeveralErrors(t *testing.T) {
err := ErrorCollector(nil, errors.New("error text"), nil)
assert.Error(t, err)
assert.Equal(t, "error text", err.Error())
}
func TestErrorCollector_EmptyErrorMessage(t *testing.T) {
err := ErrorCollector(nil, errors.New(""), nil)
assert.Error(t, err)
assert.Equal(t, "", err.Error())
}
func TestErrorCollector_AllErrors(t *testing.T) {
err := ErrorCollector(
errors.New("first"),
errors.New("second"),
errors.New("third"),
)
assert.Error(t, err)
assert.Equal(t, "first < second < third", err.Error())
}