gorm/errors.go

73 lines
1.7 KiB
Go
Raw Normal View History

2013-11-15 14:36:39 +04:00
package gorm
2015-08-13 11:42:13 +03:00
import (
"errors"
"strings"
)
2013-11-15 14:36:39 +04:00
var (
2016-03-07 16:09:05 +03:00
// ErrRecordNotFound record not found error, happens when haven't find any matched data when looking up with a struct
2016-03-07 09:54:20 +03:00
ErrRecordNotFound = errors.New("record not found")
2016-03-07 16:09:05 +03:00
// ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL
2016-03-07 09:54:20 +03:00
ErrInvalidSQL = errors.New("invalid SQL")
// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidTransaction = errors.New("no valid transaction")
// ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin`
ErrCantStartTransaction = errors.New("can't start transaction")
// ErrUnaddressable unaddressable value
ErrUnaddressable = errors.New("using unaddressable value")
2013-11-15 14:36:39 +04:00
)
2015-08-13 11:42:13 +03:00
2016-03-07 09:54:20 +03:00
// Errors contains all happened errors
type Errors []error
2015-08-13 11:42:13 +03:00
2018-02-12 04:38:16 +03:00
// IsRecordNotFoundError returns current error has record not found error or not
func IsRecordNotFoundError(err error) bool {
if errs, ok := err.(Errors); ok {
for _, err := range errs {
if err == ErrRecordNotFound {
return true
}
}
}
return err == ErrRecordNotFound
}
// GetErrors gets all happened errors
2015-08-14 07:29:53 +03:00
func (errs Errors) GetErrors() []error {
return errs
2015-08-13 11:42:13 +03:00
}
// Add adds an error
func (errs Errors) Add(newErrors ...error) Errors {
for _, err := range newErrors {
2017-09-04 17:25:57 +03:00
if err == nil {
continue
}
if errors, ok := err.(Errors); ok {
errs = errs.Add(errors...)
} else {
ok = true
for _, e := range errs {
if err == e {
ok = false
}
}
if ok {
errs = append(errs, err)
2015-08-18 06:06:10 +03:00
}
}
}
return errs
2015-08-13 11:42:13 +03:00
}
2016-03-07 09:54:20 +03:00
// Error format happened errors
2015-08-13 11:42:13 +03:00
func (errs Errors) Error() string {
var errors = []string{}
for _, e := range errs {
2015-08-13 11:42:13 +03:00
errors = append(errors, e.Error())
}
return strings.Join(errors, "; ")
}