-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimestamped_error.go
84 lines (71 loc) · 2.08 KB
/
timestamped_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
package main
import (
"fmt"
"time"
"github.com/aisbergg/go-bruh/pkg/bruh"
)
func main() {
err := foo()
switch t := err.(type) {
case *TimestampedError:
fmt.Printf("timestamp error:\n time: %s\n msg: %s\n", t.Timestamp().Format(time.RFC3339), t)
case *bruh.TraceableError:
fmt.Println("bruh error:", t)
default:
fmt.Println("other error:", t)
}
}
// -----------------------------------------------------------------------------
// The custom error
// -----------------------------------------------------------------------------
// TimestampedError is a custom error that contains a timestamp.
type TimestampedError struct {
bruh.TraceableError
timestamp time.Time
}
// TErrorf creates a new TimestampedError with a formatted message.
func TErrorf(format string, args ...any) error {
return &TimestampedError{
// skip is required to skip the current function and thus exclude this
// function from the stack trace
TraceableError: *bruh.ErrorfSkip(1, format, args...),
timestamp: time.Now(),
}
}
// TEWrapf wraps an error with a formatted message.
func TEWrapf(err error, format string, args ...any) error {
// Easiest way to change the final error message is to change it early on.
// Here we include the timestamp in the message.
ts := time.Now()
msg := fmt.Sprintf(format, args...)
msg = fmt.Sprintf("[%s] %s", ts.Format(time.RFC3339), msg)
return &TimestampedError{
TraceableError: *bruh.WrapSkip(err, 1, msg),
timestamp: ts,
}
}
// Timestamp returns the timestamp of the error.
func (te *TimestampedError) Timestamp() time.Time {
return te.timestamp
}
// -----------------------------------------------------------------------------
// Just some functions that return errors
// -----------------------------------------------------------------------------
func foo() error {
err := bar()
if err != nil {
return TEWrapf(err, "foo: failed to read config file")
}
return nil
}
func bar() error {
err := baz()
if err != nil {
return bruh.Wrapf(err, "bar: failed to parse")
}
return nil
}
func baz() error {
// external error
return fmt.Errorf("oh no")
}