-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.go
79 lines (67 loc) · 1.66 KB
/
time.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
// Copyright (c) 2021, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
"fmt"
"time"
)
// Timer interfaces provide access to a [time.Time] indicating when the error
// occurred.
type Timer interface {
error
Time() time.Time
}
type TimerSetter interface {
Timer
SetTime(time.Time)
}
// WithTime adds time information to the error. It does so by wrapping the
// error with a [Timer], or update/set the time when error implements
// [TimerSetter]. It will return nil when the provided error is nil.
func WithTime(err error, when time.Time) Timer {
if err == nil {
return nil
}
//goland:noinspection GoTypeAssertionOnErrors
if e, ok := err.(TimerSetter); ok {
e.SetTime(when)
return e
}
return &dateTimeError{
embedError: &embedError{error: err},
time: when,
}
}
// GetTime returns the [time.Time] of the last found [Timer] in err's error
// chain. If none is found, it returns the provided value or.
func GetTime(err error) (time.Time, bool) {
var dt time.Time
var has bool
for {
//goland:noinspection GoTypeAssertionOnErrors
if e, ok := err.(Timer); ok {
dt = e.Time()
has = true
}
err = Unwrap(err)
if err == nil {
break
}
}
return dt, has
}
type dateTimeError struct {
*embedError
time time.Time
}
func (e *dateTimeError) SetTime(t time.Time) { e.time = t }
func (e *dateTimeError) Time() time.Time { return e.time }
// GoString prints the error in basic Go syntax.
func (e *dateTimeError) GoString() string {
return fmt.Sprintf(
"errors.dateTimeError{time: %s, embedErr: %#v}",
e.time.String(),
e.error,
)
}