Skip to content

Use error structs instead of duplicated strings #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package mapstructure

import (
"fmt"
"reflect"
)

// DecodeError is a generic error type that holds information about
// a decoding error together with the name of the field that caused the error.
type DecodeError struct {
name string
err error
}

func newDecodeError(name string, err error) *DecodeError {
return &DecodeError{
name: name,
err: err,
}
}

func (e *DecodeError) Name() string {
return e.name
}

func (e *DecodeError) Unwrap() error {
return e.err
}

func (e *DecodeError) Error() string {
return fmt.Sprintf("'%s' %s", e.name, e.err)
}

// ParseError is an error type that indicates a value could not be parsed
// into the expected type.
type ParseError struct {
Expected reflect.Value
Value interface{}
Err error
}

func (e *ParseError) Error() string {
return fmt.Sprintf("cannot parse '%s' as '%s': %s",
e.Value, e.Expected.Type(), e.Err)
}

// UnconvertibleTypeError is an error type that indicates a value could not be
// converted to the expected type.
type UnconvertibleTypeError struct {
Expected reflect.Value
Value interface{}
}

func (e *UnconvertibleTypeError) Error() string {
return fmt.Sprintf("expected type '%s', got unconvertible type '%s', value: '%v'",
e.Expected.Type(), reflect.TypeOf(e.Value), e.Value)
}
Loading
Loading