-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoops.go
More file actions
84 lines (72 loc) · 1.84 KB
/
Copy pathoops.go
File metadata and controls
84 lines (72 loc) · 1.84 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
73
74
75
76
77
78
79
80
81
82
83
84
package oops
import (
"errors"
"fmt"
)
// sourceEnabled is a package variable to enable/disable tracking the source location.
var sourceEnabled = true
// New returns a new oops error.
func New(msg string) *Error {
var sources []Source
if s := source(); s != nil {
sources = append(sources, *s)
}
return &Error{err: errors.New(msg), sources: sources}
}
// Wrap wraps an error as an oops error.
// supports supports [string, any]... pairs or slog.Attr values.
func Wrap(err error, args ...any) error {
if err == nil {
return nil
}
var sources []Source
if s := source(); s != nil {
sources = append(sources, *s)
}
var oops *Error
if errors.As(err, &oops) {
return &Error{
err: err,
attributes: argsToAttr(oops.attributes, args),
sources: append(oops.sources, sources...),
code: oops.code,
}
}
return &Error{err: err, attributes: argsToAttr(nil, args), sources: sources}
}
// Errorf formats a string and returns a new oops error.
func Errorf(format string, args ...any) *Error {
var sources []Source
if s := source(); s != nil {
sources = append(sources, *s)
}
e := &Error{err: fmt.Errorf(format, args...), sources: sources}
for _, arg := range args {
if err, ok := arg.(error); ok {
var oops *Error
if errors.As(err, &oops) {
e.attributes = oops.attributes
e.sources = append(e.sources, oops.sources...)
}
}
}
return e
}
// Code returns the oops error code, if the error is an oops error.
// if the error code is not set, it looks for a "code" attribute set to an int.
func Code(err error) int {
var e *Error
if errors.As(err, &e) {
if e.code > 0 {
return e.code
} else if code, ok := e.attributes["code"].(int); ok {
return code
}
}
return 0
}
// EnableSource enables or disables source tracking.
// default is true.
func EnableSource(enabled bool) {
sourceEnabled = enabled
}