aboutsummaryrefslogtreecommitdiffstats
path: root/errors.go
blob: cb356be6ff995cdea80350dfe3fcb063c301a6b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package envelope

import (
	"fmt"
	"reflect"
)

// BaseError represents the base error type for the envelope package
type BaseError struct {
	// Message is a human-readable error description
	Message string
	// Err is the underlying error, if any
	Err error
}

func (e *BaseError) Error() string {
	if e.Err != nil {
		return fmt.Sprintf("%s: %v", e.Message, e.Err)
	}
	return e.Message
}

func (e *BaseError) Unwrap() error {
	return e.Err
}

type NotPointerToStructError struct {
	BaseError
	ActualType reflect.Type
}

func (e *NotPointerToStructError) Error() string {
	return e.Message
}

func newNotPointerToStructError(t reflect.Type) *NotPointerToStructError {
	return &NotPointerToStructError{
		BaseError: BaseError{
			Message: "value must be a pointer to a struct",
		},
		ActualType: t,
	}
}

// UnsupportedTypeError is returned when a field has a type that cannot be parsed
type UnsupportedTypeError struct {
	BaseError
	// FieldName is the name of the field with the unsupported type
	FieldName string
	// FieldType is the unsupported type
	FieldType reflect.Type
}

func (e *UnsupportedTypeError) Error() string {
	return e.Message
}

func newUnsupportedTypeError(fieldName string, fieldType reflect.Type) *UnsupportedTypeError {
	return &UnsupportedTypeError{
		BaseError: BaseError{
			Message: fmt.Sprintf("unsupported field type for field %s", fieldName),
		},
		FieldName: fieldName,
		FieldType: fieldType,
	}
}

// ParseError is returned when a value cannot be parsed into the desired type
type ParseError struct {
	BaseError
	// FieldName is the name of the field being parsed
	FieldName string
	// EnvName is the name of the environment variable
	EnvName string
	// Value is the string value that could not be parsed
	Value string
	// TargetType is the type that the value could not be parsed into
	TargetType reflect.Type
}

func (e *ParseError) Error() string {
	return e.Message
}

func newParseError(fieldName string, envName string, value string, targetType reflect.Type, err error) *ParseError {
	return &ParseError{
		BaseError: BaseError{
			Message: fmt.Sprintf("error parsing value '%s' to '%v' for field '%s' from environment variable '%s'", value, targetType, fieldName, envName),
			Err:     err,
		},
		FieldName:  fieldName,
		EnvName:    envName,
		Value:      value,
		TargetType: targetType,
	}
}