-
Notifications
You must be signed in to change notification settings - Fork 19
/
error.go
101 lines (83 loc) · 1.79 KB
/
error.go
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
97
98
99
100
101
// Code generated by 'go generate'
package optional
import (
"encoding/json"
"errors"
)
// Error is an optional error.
type Error struct {
value *error
}
// NewError creates an optional.Error from a error.
func NewError(v error) Error {
return Error{&v}
}
// NewErrorFromPtr creates an optional.Error from a error pointer.
func NewErrorFromPtr(v *error) Error {
if v == nil {
return Error{}
}
return NewError(*v)
}
// Set sets the error value.
func (e *Error) Set(v error) {
e.value = &v
}
// ToPtr returns a *error of the value or nil if not present.
func (e Error) ToPtr() *error {
if !e.Present() {
return nil
}
v := *e.value
return &v
}
// Get returns the error value or an error if not present.
func (e Error) Get() (error, error) {
if !e.Present() {
var zero error
return zero, errors.New("value not present")
}
return *e.value, nil
}
// MustGet returns the error value or panics if not present.
func (e Error) MustGet() error {
if !e.Present() {
panic("value not present")
}
return *e.value
}
// Present returns whether or not the value is present.
func (e Error) Present() bool {
return e.value != nil
}
// OrElse returns the error value or a default value if the value is not present.
func (e Error) OrElse(v error) error {
if e.Present() {
return *e.value
}
return v
}
// If calls the function f with the value if the value is present.
func (e Error) If(fn func(error)) {
if e.Present() {
fn(*e.value)
}
}
func (e Error) MarshalJSON() ([]byte, error) {
if e.Present() {
return json.Marshal(e.value)
}
return json.Marshal(nil)
}
func (e *Error) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
e.value = nil
return nil
}
var value error
if err := json.Unmarshal(data, &value); err != nil {
return err
}
e.value = &value
return nil
}