From fc3f62ed9d1c3d33208a670d8ab471a7bbbb30bb Mon Sep 17 00:00:00 2001 From: Yasss Date: Thu, 9 May 2019 15:26:26 +0200 Subject: [PATCH] Add a type that implements error interface instead of using an alias --- backend/file/file.go | 11 +++++++++-- backend/file/file_test.go | 2 +- config.go | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/backend/file/file.go b/backend/file/file.go index b9a7a54..dc1d988 100644 --- a/backend/file/file.go +++ b/backend/file/file.go @@ -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. @@ -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) } diff --git a/backend/file/file_test.go b/backend/file/file_test.go index bbeead1..cc2fddf 100644 --- a/backend/file/file_test.go +++ b/backend/file/file_test.go @@ -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) }) } diff --git a/config.go b/config.go index cee5d97..ec819f7 100644 --- a/config.go +++ b/config.go @@ -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 }