Skip to content

Commit

Permalink
Add NotFound()
Browse files Browse the repository at this point in the history
  • Loading branch information
yuin committed Aug 6, 2023
1 parent d39d347 commit afce4e8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,10 @@ type delegatingMappers struct {

func (d *delegatingMappers) Get(name string) (any, error) {
v, err := d.Mappers.Get(name)
if err != nil && strings.Contains(err.Error(), "not found") {
var merr interface {
NotFound() bool
}
if errors.As(err, &merr) && merr.NotFound() {
return d.parent.Get(name)
}
return v, err
Expand Down
25 changes: 23 additions & 2 deletions mappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ func (s *singleton[T]) MustGet() T {
return instance
}
type merror struct {
error
notFound bool
}
func (e *merror) NotFound() bool {
return e.notFound
}
func (e *merror) Unwrap() error {
return e.error
}
type MapperGetter = ` + mapperGetterSrc + `
// Mappers is a collection of mappers.
Expand Down Expand Up @@ -141,11 +154,19 @@ func (d *mappers) Get(name string) (any, error) {
if fok && factory != nil {
obj, err := factory.(func(*mappers) (any, error))(d)
if err != nil {
return nil, fmt.Errorf("Failed to create a mapper: %%w", err)
merr := &merror {
error: err,
notFound: false,
}
return nil, fmt.Errorf("Failed to create a mapper: %%w", merr)
}
d.dependencies.Store(name, obj)
} else {
return nil, fmt.Errorf("Object %%s not found", name)
merr := &merror {
error: fmt.Errorf("Object %%s not found", name),
notFound: true,
}
return nil, merr
}
}
obj, _ := d.dependencies.Load(name)
Expand Down
12 changes: 12 additions & 0 deletions testdata/testmod/mapper/todo_mapper_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mapper_test

import (
"errors"
"testing"
"time"

Expand Down Expand Up @@ -241,3 +242,14 @@ func TestNilCollection(t *testing.T) {
}

}

func TestMapperNotFound(t *testing.T) {
mappers := NewMappers()
_, err := mappers.Get("Dummy")
var merr interface {
NotFound() bool
}
if !errors.As(err, &merr) || !merr.NotFound() {
t.Errorf("error should be a not found error")
}
}

0 comments on commit afce4e8

Please sign in to comment.