Debian Codegraph @

util/error.go

raw
1 package util
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log/slog"
8 )
9
10 type ContextualError struct {
11 RealError error
12 Fields map[string]any
13 Context string
14 }
15
16 func NewContextualError(msg string, fields map[string]any, realError error) *ContextualError {
17 return &ContextualError{Context: msg, Fields: fields, RealError: realError}
18 }
19
20 // ContextualizeIfNeeded is a helper function to turn an error into a ContextualError if it is not already one
21 func ContextualizeIfNeeded(msg string, err error) error {
22 switch err.(type) {
23 case *ContextualError:
24 return err
25 default:
26 return NewContextualError(msg, nil, err)
27 }
28 }
29
30 // LogWithContextIfNeeded is a helper function to log an error line for an error or ContextualError
31 func LogWithContextIfNeeded(msg string, err error, l *slog.Logger) {
32 switch v := err.(type) {
33 case *ContextualError:
34 v.Log(l)
35 default:
36 l.Error(msg, "error", err)
37 }
38 }
39
40 func (ce *ContextualError) Error() string {
41 if ce.RealError == nil {
42 return ce.Context
43 }
44 return fmt.Errorf("%s (%v): %w", ce.Context, ce.Fields, ce.RealError).Error()
45 }
46
47 func (ce *ContextualError) Unwrap() error {
48 if ce.RealError == nil {
49 return errors.New(ce.Context)
50 }
51 return ce.RealError
52 }
53
54 // Log emits ce as a single error-level log line with Fields and RealError
55 // promoted to top-level attributes, producing a flat shape callers can grep
56 // or parse without walking into a nested object.
57 func (ce *ContextualError) Log(l *slog.Logger) {
58 attrs := make([]slog.Attr, 0, len(ce.Fields)+1)
59 for k, v := range ce.Fields {
60 attrs = append(attrs, slog.Any(k, v))
61 }
62 if ce.RealError != nil {
63 attrs = append(attrs, slog.Any("error", ce.RealError))
64 }
65 // LogAttrs is intentional: attrs is built from a map[string]any so it has
66 // no pair-form equivalent.
67 //nolint:sloglint
68 l.LogAttrs(context.Background(), slog.LevelError, ce.Context, attrs...)
69 }