mirror of
https://github.com/retailcrm/mg-transport-core.git
synced 2024-11-22 05:06:04 +03:00
error collector (mostly for migrations)
This commit is contained in:
parent
f2b79fad5c
commit
06cab9921d
38
core/error_collector.go
Normal file
38
core/error_collector.go
Normal 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
|
||||
}
|
40
core/error_collector_test.go
Normal file
40
core/error_collector_test.go
Normal 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())
|
||||
}
|
Loading…
Reference in New Issue
Block a user