From a9b21cd70827058ae9ce90a459d303b27b34e420 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Mendelski?= Date: Sat, 4 Mar 2023 12:52:37 +0100 Subject: [PATCH] Fix nil error value returned from a provider --- Makefile | 2 +- holder.go | 13 +++++++++---- test/lazy_dependency_test.go | 5 +++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index cf882c4..d95489f 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/holder.go b/holder.go index b00045a..beed496 100644 --- a/holder.go +++ b/holder.go @@ -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() @@ -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 } diff --git a/test/lazy_dependency_test.go b/test/lazy_dependency_test.go index 7fa9ddb..aedf74a 100644 --- a/test/lazy_dependency_test.go +++ b/test/lazy_dependency_test.go @@ -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 }) },