Skip to content

Commit

Permalink
Send an error when no provider.
Browse files Browse the repository at this point in the history
  • Loading branch information
googollee committed Apr 9, 2024
1 parent a21054c commit 1e664d2
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
3 changes: 2 additions & 1 deletion module/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package module

import (
"context"
"fmt"
)

type createPanic struct {
Expand All @@ -27,7 +28,7 @@ func (c *moduleContext) Value(key any) any {

provider, ok := c.providers[moduleKey]
if !ok {
return nil
panic(createPanic{key: moduleKey, err: fmt.Errorf("can't find module provideing %q", moduleKey)})
}

instance, err := provider.value(c)
Expand Down
9 changes: 3 additions & 6 deletions module/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ type Cache struct {

func NewCache(ctx context.Context) (*Cache, error) {
db := ModuleDB.Value(ctx)
if db == nil {
return nil, fmt.Errorf("no db as fallback")
}
return &Cache{
fallback: db,
}, nil
Expand Down Expand Up @@ -190,7 +187,7 @@ func ExampleModule_notExistingProvider() {
}

// Output:
// inject error: module *module_test.Cache creates an instance error: no db as fallback
// inject error: module module_test.DB creates an instance error: can't find module provideing "module_test.DB"
}

type FileSystem interface {
Expand Down Expand Up @@ -223,13 +220,13 @@ func (f *mockFileSystem) Write() {}
func ExampleModule_duplicatingProviders() {
defer func() {
p := recover().(string)
fmt.Println("panic:", regexp.MustCompile(`at .*\/go-espresso`).ReplaceAllString(p, "at .../go-espresso"))
fmt.Println("panic:", regexp.MustCompile(`at .*`).ReplaceAllString(p, "at <removed file and line>"))
}()

repo := module.NewRepo()
repo.AddModule(RealFileSystem)
repo.AddModule(MockFileSystem)

// Output:
// panic: already have a provider with type "module_test.FileSystem", added at .../go-espresso/module/example_test.go:230
// panic: already have a provider with type "module_test.FileSystem", added at <removed file and line>
}

0 comments on commit 1e664d2

Please sign in to comment.