diff --git a/module/context.go b/module/context.go index 8c101f1..09d4c36 100644 --- a/module/context.go +++ b/module/context.go @@ -5,6 +5,8 @@ import ( "fmt" ) +var ErrNoPrivoder = fmt.Errorf("can't find module") + type createPanic struct { key moduleKey err error @@ -28,7 +30,7 @@ func (c *moduleContext) Value(key any) any { provider, ok := c.providers[moduleKey] if !ok { - panic(createPanic{key: moduleKey, err: fmt.Errorf("can't find module provideing %q", moduleKey)}) + panic(createPanic{key: moduleKey, err: ErrNoPrivoder}) } instance, err := provider.value(c) diff --git a/module/example_test.go b/module/example_test.go index 654ece0..8be144c 100644 --- a/module/example_test.go +++ b/module/example_test.go @@ -135,7 +135,7 @@ func ExampleModule_createWithError() { } // Output: - // inject error: module *module_test.Cache creates an instance error: new cache error + // inject error: creating with module *module_test.Cache: new cache error } func ExampleModule_createWithPanic() { @@ -187,7 +187,7 @@ func ExampleModule_notExistingProvider() { } // Output: - // inject error: module module_test.DB creates an instance error: can't find module provideing "module_test.DB" + // inject error: creating with module module_test.DB: can't find module } type FileSystem interface { diff --git a/module/module.go b/module/module.go index b42e765..03dfd9b 100644 --- a/module/module.go +++ b/module/module.go @@ -44,12 +44,7 @@ func (m Module[T]) Value(ctx context.Context) T { return null } - ret, ok := v.(T) - if !ok { - return null - } - - return ret + return v.(T) } func (m Module[T]) key() moduleKey { diff --git a/module/repo.go b/module/repo.go index 3c4b228..2ad6702 100644 --- a/module/repo.go +++ b/module/repo.go @@ -44,17 +44,7 @@ func (r *Repo) AddModule(provider Provider) { // It returns a new context with all injections. If any module creates an instance with an error, `InjectTo` returns that error with the module name. func (r *Repo) InjectTo(ctx context.Context) (ret context.Context, err error) { defer func() { - rErr := recover() - if rErr == nil { - return - } - - createErr, ok := rErr.(createPanic) - if !ok { - panic(rErr) - } - - err = fmt.Errorf("module %s creates an instance error: %w", createErr.key, createErr.err) + err = r.catchError(recover()) }() providers := make(map[moduleKey]Provider) @@ -74,3 +64,16 @@ func (r *Repo) InjectTo(ctx context.Context) (ret context.Context, err error) { return } + +func (r *Repo) catchError(err any) error { + if err == nil { + return nil + } + + createErr, ok := err.(createPanic) + if !ok { + panic(err) + } + + return fmt.Errorf("creating with module %s: %w", createErr.key, createErr.err) +}