Skip to content

Commit

Permalink
Add a type that implements error interface instead of using an alias
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasss committed Aug 27, 2019
1 parent 5fa198b commit fc3f62e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions backend/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ import (
)

// ErrOpenOptionalFile is returned when opening an optional file returns an error.
type ErrOpenOptionalFile error
type ErrOpenOptionalFile struct {
path string
err error
}

func (e *ErrOpenOptionalFile) Error() string {
return fmt.Sprintf("failed to open optional file at path \"%s\": %s", e.path, e.err.Error())
}

// Backend that loads a configuration from a file.
// It supports json and yaml formats.
Expand Down Expand Up @@ -45,7 +52,7 @@ func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error {
f, err := os.Open(b.path)
if err != nil {
if b.optional {
return ErrOpenOptionalFile(fmt.Errorf("failed to open optional file at path \"%s\": %s", b.path, err.Error()))
return &ErrOpenOptionalFile{path: b.path, err: err}
}
return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path)
}
Expand Down
2 changes: 1 addition & 1 deletion backend/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ timeout = 10

err := b.Unmarshal(context.Background(), &c)
require.Error(t, err)
_, ok := err.(file.ErrOpenOptionalFile)
_, ok := err.(*file.ErrOpenOptionalFile)
require.True(t, ok)
})
}
2 changes: 1 addition & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func (l *Loader) resolve(ctx context.Context, s *StructConfig) error {
if u, ok := b.(Unmarshaler); ok {
err := u.Unmarshal(ctx, s.S)
if err != nil {
if uerr, ok := err.(file.ErrOpenOptionalFile); ok {
if uerr, ok := err.(*file.ErrOpenOptionalFile); ok {
l.log.Println(uerr.Error())
continue
}
Expand Down

0 comments on commit fc3f62e

Please sign in to comment.