err.go

v0.2.0
Doc Versions Source
1
package scribe
2
3
import "log/slog"
4
5
// errValue wraps an error with a color hint for TintHandler.
6
type errValue struct {
7
	err   error
8
	color Color
9
}
10
11
// LogValue implements slog.LogValuer.
12
// Delegates to the error's LogValue if it implements slog.LogValuer,
13
// otherwise returns the error message as a string.
14
func (e errValue) LogValue() slog.Value {
15
	if e.err == nil {
16
		return slog.Value{}
17
	}
18
	// Delegate to culpa or any other LogValuer error
19
	if lv, ok := e.err.(slog.LogValuer); ok {
20
		return lv.LogValue()
21
	}
22
	return slog.StringValue(e.err.Error())
23
}
24
25
// Color returns the color hint for this error.
26
func (e errValue) Color() Color {
27
	return e.color
28
}
29
30
// Err wraps an error for logging with red color highlighting.
31
// Use this when logging errors to make them visually distinct:
32
//
33
//	logger.Error("failed", scribe.Err(err))
34
//
35
// If the error is a culpa error, its details (hint, code, etc.)
36
// and stacktrace will be extracted and formatted.
37
func Err(err error) slog.Attr {
38
	return slog.Any("err", errValue{err: err, color: Red})
39
}
40
41
// ErrAttr is like Err but allows specifying a custom key.
42
//
43
//	logger.Error("failed", scribe.ErrAttr("cause", err))
44
func ErrAttr(key string, err error) slog.Attr {
45
	return slog.Any(key, errValue{err: err, color: Red})
46
}
47

Source Files