-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
72 lines (59 loc) · 1.24 KB
/
errors.go
File metadata and controls
72 lines (59 loc) · 1.24 KB
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
package json_errors
// BaseError interface reveals
// additional information about the error.
// Implements a built-in error interface.
type BaseError interface {
Error() string
}
// baseError is a simple error struct.
type baseError struct {
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
}
// New returns a new `jerr.BaseError` with given values.
func New(message string) error {
return &baseError{
Message: escapeJSON(message),
}
}
func (e *baseError) Error() string {
msg := "{"
if e.Message != "" {
msg += `"message":"` + e.Message + `"`
}
if e.Details != "" {
if e.Details[0] == '{' {
msg += `,"details":` + e.Details
} else {
msg += `,"details":"` + e.Details + `"`
}
}
msg += "}"
return msg
}
// Wrap adds `err` to the `details` field of
// the new `jerr.BaseError`.
func Wrap(err error, message string) error {
if err == nil {
return New(message)
}
if message == "" {
switch v := err.(type) {
case *baseError:
return v
default:
return New(v.Error())
}
}
var details string
switch d := err.(type) {
case *baseError:
details = d.Error()
default:
details = escapeJSON(d.Error())
}
return &baseError{
Message: escapeJSON(message),
Details: details,
}
}