Skip to content

Commit 9661f6d

Browse files
committed
feat: add common error interface
Signed-off-by: Mark Sagi-Kazar <[email protected]>
1 parent f12f6c7 commit 9661f6d

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

errors.go

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ import (
55
"reflect"
66
)
77

8+
// Error interface is implemented by all errors emitted by mapstructure.
9+
//
10+
// Errors from underlying libraries MAY not be wrapped.
11+
//
12+
// Use [errors.As] to check if an error implements this interface.
13+
type Error interface {
14+
error
15+
16+
mapstructure()
17+
}
18+
819
// DecodeError is a generic error type that holds information about
920
// a decoding error together with the name of the field that caused the error.
1021
type DecodeError struct {
@@ -28,30 +39,39 @@ func (e *DecodeError) Unwrap() error {
2839
}
2940

3041
func (e *DecodeError) Error() string {
31-
return fmt.Sprintf("'%s' %s", e.name, e.err)
42+
return fmt.Sprintf("decoding '%s': %s", e.name, e.err)
3243
}
3344

45+
func (*DecodeError) mapstructure() {}
46+
3447
// ParseError is an error type that indicates a value could not be parsed
3548
// into the expected type.
3649
type ParseError struct {
3750
Expected reflect.Value
38-
Value interface{}
51+
Value any
3952
Err error
4053
}
4154

4255
func (e *ParseError) Error() string {
43-
return fmt.Sprintf("cannot parse '%s' as '%s': %s",
44-
e.Value, e.Expected.Type(), e.Err)
56+
return fmt.Sprintf("cannot parse '%s' as '%s': %s", e.Value, e.Expected.Type(), e.Err)
4557
}
4658

59+
func (*ParseError) mapstructure() {}
60+
4761
// UnconvertibleTypeError is an error type that indicates a value could not be
4862
// converted to the expected type.
4963
type UnconvertibleTypeError struct {
5064
Expected reflect.Value
51-
Value interface{}
65+
Value any
5266
}
5367

5468
func (e *UnconvertibleTypeError) Error() string {
55-
return fmt.Sprintf("expected type '%s', got unconvertible type '%s', value: '%v'",
56-
e.Expected.Type(), reflect.TypeOf(e.Value), e.Value)
69+
return fmt.Sprintf(
70+
"expected type '%s', got unconvertible type '%s', value: '%v'",
71+
e.Expected.Type(),
72+
reflect.TypeOf(e.Value),
73+
e.Value,
74+
)
5775
}
76+
77+
func (*UnconvertibleTypeError) mapstructure() {}

0 commit comments

Comments
 (0)