dig icon indicating copy to clipboard operation
dig copied to clipboard

Not providing any value group does not return an error during invocation

Open paullen opened this issue 2 years ago • 1 comments

Describe the bug While requesting a value group in the input, in the Invoke method, dig does not check for the existence of any providers of the value group.

To Reproduce

Run the following code. The function is invoked without letting me know that there are no value group providers.

package main

import (
	"fmt"
	"log"

	"go.uber.org/dig"
)

type Logger struct{}
type LogType string

const (
	LogType_ERROR   LogType = "ERROR"
	LogType_INFO    LogType = "INFO"
	LogType_WARNING LogType = "WARNING"
)

func (l Logger) Log(logType LogType, message string) {
	log.Println(logType, message)
}

type HttpClient struct {
	logger *Logger
}

func (client *HttpClient) Get(url string) (string, error) {
	client.logger.Log(LogType_INFO, "getting "+url)

	return "You got " + url, nil
}

type HttpClientInput struct {
	dig.In
	Loggers []*Logger `group:"loggers"`
}

func NewHttpClient(input HttpClientInput) *HttpClient {
	if len(input.Loggers) > 0 {
		return &HttpClient{logger: input.Loggers[0]}
	} else {
		panic("should not execute")
	}
}

func BuildContainer() *dig.Container {
	container := dig.New()

	if err := container.Provide(NewHttpClient); err != nil {
		log.Println(err)
	}

	return container
}

func ExecuteFunction(client *HttpClient) {
	res, _ := client.Get("foo.bar")

	fmt.Println(res)
}

func main() {
	container := BuildContainer()

	if err := container.Invoke(ExecuteFunction); err != nil {
		log.Println(err)
	}

}

Expected behavior The expected behaviour would be to return an error in the Invoke function after checking for providers.

Additional context If this is by design, could you suggest ways to implement this kind of a check using current methods.

paullen avatar Jun 08 '23 21:06 paullen

Hey @paullen - as I mentioned in #184, this shouldn't be changed blindly as it would break a lot of users, but I think it's a good idea to add an option that can be passed to Dig to check for this.

JacobOaks avatar Apr 29 '24 14:04 JacobOaks