Skip to content

Commit f12f6c7

Browse files
Merge pull request #102 from m1k1o/prettify-errors2
Use error structs instead of duplicated strings
2 parents 1a66224 + b82cfe5 commit f12f6c7

File tree

3 files changed

+182
-62
lines changed

3 files changed

+182
-62
lines changed

‎errors.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package mapstructure
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
)
7+
8+
// DecodeError is a generic error type that holds information about
9+
// a decoding error together with the name of the field that caused the error.
10+
type DecodeError struct {
11+
name string
12+
err error
13+
}
14+
15+
func newDecodeError(name string, err error) *DecodeError {
16+
return &DecodeError{
17+
name: name,
18+
err: err,
19+
}
20+
}
21+
22+
func (e *DecodeError) Name() string {
23+
return e.name
24+
}
25+
26+
func (e *DecodeError) Unwrap() error {
27+
return e.err
28+
}
29+
30+
func (e *DecodeError) Error() string {
31+
return fmt.Sprintf("'%s' %s", e.name, e.err)
32+
}
33+
34+
// ParseError is an error type that indicates a value could not be parsed
35+
// into the expected type.
36+
type ParseError struct {
37+
Expected reflect.Value
38+
Value interface{}
39+
Err error
40+
}
41+
42+
func (e *ParseError) Error() string {
43+
return fmt.Sprintf("cannot parse '%s' as '%s': %s",
44+
e.Value, e.Expected.Type(), e.Err)
45+
}
46+
47+
// UnconvertibleTypeError is an error type that indicates a value could not be
48+
// converted to the expected type.
49+
type UnconvertibleTypeError struct {
50+
Expected reflect.Value
51+
Value interface{}
52+
}
53+
54+
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)
57+
}

0 commit comments

Comments
 (0)