Skip to content

Commit

Permalink
Merge pull request #1 from aybabtme/clearer_error
Browse files Browse the repository at this point in the history
Contextual info to error messages
  • Loading branch information
kelseyhightower committed Mar 15, 2014
2 parents 6ca6163 + 1293a40 commit 0280e33
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions envconfig.go
Expand Up @@ -19,13 +19,14 @@ var ErrInvalidSpecification = errors.New("invalid specification must be a struct
// A ParseError occurs when an environment variable cannot be converted to
// the type required by a struct field during assignment.
type ParseError struct {
KeyName string
FieldName string
TypeName string
Value string
}

func (e *ParseError) Error() string {
return fmt.Sprintf("envconfig.Process: assigning to %s: converting '%s' to an %s", e.FieldName, e.Value, e.TypeName)
return fmt.Sprintf("envconfig.Process: assigning %[1]s to %[2]s: converting '%[3]s' to type %[4]s", e.KeyName, e.FieldName, e.Value, e.TypeName)
}

func Process(prefix string, spec interface{}) error {
Expand All @@ -38,8 +39,8 @@ func Process(prefix string, spec interface{}) error {
f := s.Field(i)
if f.CanSet() {
fieldName := typeOfSpec.Field(i).Name
key := fmt.Sprintf("%s_%s", prefix, fieldName)
value := os.Getenv(strings.ToUpper(key))
key := strings.ToUpper(fmt.Sprintf("%s_%s", prefix, fieldName))
value := os.Getenv(key)
if value == "" {
continue
}
Expand All @@ -50,8 +51,9 @@ func Process(prefix string, spec interface{}) error {
intValue, err := strconv.ParseInt(value, 0, f.Type().Bits())
if err != nil {
return &ParseError{
KeyName: key,
FieldName: fieldName,
TypeName: f.Kind().String(),
TypeName: f.Type().String(),
Value: value,
}
}
Expand All @@ -60,8 +62,9 @@ func Process(prefix string, spec interface{}) error {
boolValue, err := strconv.ParseBool(value)
if err != nil {
return &ParseError{
KeyName: key,
FieldName: fieldName,
TypeName: f.Kind().String(),
TypeName: f.Type().String(),
Value: value,
}
}
Expand All @@ -70,8 +73,9 @@ func Process(prefix string, spec interface{}) error {
floatValue, err := strconv.ParseFloat(value, f.Type().Bits())
if err != nil {
return &ParseError{
KeyName: key,
FieldName: fieldName,
TypeName: f.Kind().String(),
TypeName: f.Type().String(),
Value: value,
}
}
Expand Down

0 comments on commit 0280e33

Please sign in to comment.