generated from skeptycal/gorepotemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_func.go
54 lines (46 loc) · 1.3 KB
/
error_func.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
// Copyright (c) 2021 Michael Treanor
// https://github.com/skeptycal
// MIT License
package errorlogger
import (
"github.com/pkg/errors"
)
// Disable disables logging and sets a no-op function for
// Err() to prevent slowdowns while logging is disabled.
func (e *errorLogger) Disable() {
e.errFunc = e.noErr
}
// Enable enables logging and restores the Err() logging functionality.
func (e *errorLogger) Enable() {
e.errFunc = e.yesErr
}
// Err logs an error to the provided logger, if it is enabled,
// and returns the error unchanged to be propagated up.
func (e *errorLogger) Err(err error) error {
if err == nil {
return nil
}
return e.errFunc(err)
}
// noErr is a no-op errorFunc for disabling logging without
// constant repetitive flag checks or other hacks.
// https://en.wikipedia.org/wiki/NOP_(code)
func (e *errorLogger) noErr(err error) error {
// TODO does this really need to return an error?
// TODO does the compiler remove this?
// TODO would a pointer be better here? *(&err)
// TODO does the compiler remove this?
return err
}
// yesErr is an errorFunc that logs and wraps an error, then
// returns the error unchanged.
func (e *errorLogger) yesErr(err error) error {
if err == nil {
return nil
}
if e.wrap != nil {
err = errors.Wrap(err, e.wrap.Error())
}
e.logFunc(err)
return err
}