externalize error formats + strings

This commit is contained in:
parent 4834dc5908
commit 26101760cc
Signed by: tablet
GPG Key ID: 924A5F6AF051E87C
4 changed files with 28 additions and 8 deletions

20
errors.go Normal file

@ -0,0 +1,20 @@
package orm
import (
"errors"
)
var (
ErrNotASlice = errors.New("Current object or field is not a slice!")
ErrNotAStruct = errors.New("Current object or field is not a struct!")
ErrOutOfBounds = errors.New("Index(es) out of bounds!")
ErrAppendMultipleDocuments = errors.New("Cannot append to multiple documents!")
ErrNotSliceOrStruct = errors.New("Current object or field is not a slice nor a struct!")
)
const (
errFmtMalformedField = "Malformed field name passed: '%s'"
errFmtNotAModel = "Type '%s' is not a model"
errFmtNotHasID = "Type '%s' does not implement HasID"
errFmtModelNotRegistered = "Model not registered for type: '%s'"
)

@ -259,7 +259,7 @@ func (m *Model) Append(field string, a ...interface{}) error {
fv = fv.Elem()
}
if fv.Kind() != reflect.Slice {
return fmt.Errorf("Current object is not a slice!")
return ErrNotASlice
}
for _, b := range a {
val := reflect.ValueOf(incrementTagged(b))
@ -291,7 +291,7 @@ func (m *Model) Pull(field string, a ...any) error {
fv = fv.Elem()
}
if fv.Kind() != reflect.Slice {
return fmt.Errorf("Current object is not a slice!")
return ErrNotASlice
}
outer:
for _, b := range a {
@ -332,7 +332,7 @@ func (m *Model) Swap(field string, i, j int) error {
return err
}
if i >= fv.Len() || j >= fv.Len() {
return fmt.Errorf("index(es) out of bounds")
return ErrOutOfBounds
}
oi := fv.Index(i).Interface()
oj := fv.Index(j).Interface()

@ -127,7 +127,7 @@ func doSave(c *mongo.Collection, isNew bool, arg interface{}) error {
var err error
m, ok := arg.(IModel)
if !ok {
return fmt.Errorf("type '%s' is not a model", nameOf(arg))
return fmt.Errorf(errFmtNotAModel, nameOf(arg))
}
m.setSelf(m)
now := time.Now()
@ -170,7 +170,7 @@ func doDelete(m *Model, arg interface{}) error {
self, ok := arg.(HasID)
if !ok {
return fmt.Errorf("Object '%s' does not implement HasID", nameOf(arg))
return fmt.Errorf(errFmtNotHasID, nameOf(arg))
}
c := m.getColl()
_, err := c.DeleteOne(context.TODO(), bson.M{"_id": self.Id()})

@ -148,17 +148,17 @@ func pull(s reflect.Value, idx int, typ reflect.Type) reflect.Value {
func checkStruct(ref reflect.Value) error {
if ref.Kind() == reflect.Slice {
return fmt.Errorf("Cannot append to multiple documents!")
return ErrAppendMultipleDocuments
}
if ref.Kind() != reflect.Struct {
return fmt.Errorf("Current object is not a struct!")
return ErrNotAStruct
}
return nil
}
func checkSlice(ref reflect.Value) error {
if ref.Kind() != reflect.Slice {
return fmt.Errorf("Current field is not a slice!")
return ErrNotASlice
}
return nil
}