Skip to content

Commit

Permalink
Fix nil error value returned from a provider
Browse files Browse the repository at this point in the history
  • Loading branch information
pmendelski committed Mar 4, 2023
1 parent bbbcea0 commit a9b21cd
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ format: ## Format source files
.PHONY: outdated
outdated: ## Print outdated dependencies
@go mod tidy
@go list -u -m -json all | $(GOMODOUDATED_CMD) -update -direct
@go list -u -m -json all | $(GOMODOUTDATED_CMD) -update -direct

.PHONY: weight
weight: ## Print info about package weight
Expand Down
13 changes: 9 additions & 4 deletions holder.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ func createLazyHolder(ctor any) (*holder, *Error) {
if ctype.IsVariadic() {
return nil, newInvalidConstructorError("variadic parameters not supported (use slice instead)")
}
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
if numResults == 2 && !ctype.Out(1).AssignableTo(errorInterface) {
return nil, newInvalidConstructorError("expected second result value to be an error")
if numResults == 2 {
outtype := reflect.New(ctype.Out(1))
if _, ok := outtype.Interface().(*error); !ok {
return nil, newInvalidConstructorError("expected second result value to be an error")
}
}
resultType := ctype.Out(0)
numArgs := ctype.NumIn()
Expand Down Expand Up @@ -75,9 +77,12 @@ func createLazyHolder(ctor any) (*holder, *Error) {
result := cval.Call(args)
obj := result[0].Interface()
if len(result) == 2 {
if result[1].IsNil() {
return obj, nil
}
err, ok := result[1].Interface().(error)
if !ok {
return nil, newInvalidConstructorError("expected second result value to be an error")
return nil, newInvalidConstructorError("expected second result value to be an error xxxx")
}
return obj, err
}
Expand Down
5 changes: 5 additions & 0 deletions test/lazy_dependency_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ func (suite *LazyDependencySuite) TestGetByType() {
provide: func(ctxb *di.ContextBuilder) { ctxb.Provide(func() *Foo { return &foo }) },
get: func(ctx *di.Context) (any, error) { return di.GetOrErr[*Foo](ctx) },
},
{
value: &foo,
provide: func(ctxb *di.ContextBuilder) { ctxb.Provide(func() (*Foo, error) { return &foo, nil }) },
get: func(ctx *di.Context) (any, error) { return di.GetOrErr[*Foo](ctx) },
},
{
value: foo,
provide: func(ctxb *di.ContextBuilder) { ctxb.Provide(func() Foo { return foo }) },
Expand Down

0 comments on commit a9b21cd

Please sign in to comment.