wrap returns the error wrapped with the calling function name and optional extra context strings as prefix. A nil error wraps to nil.
(err error, context ...string)
| 97 | // wrap returns the error wrapped with the calling function name and |
| 98 | // optional extra context strings as prefix. A nil error wraps to nil. |
| 99 | func wrap(err error, context ...string) error { |
| 100 | if err == nil { |
| 101 | return nil |
| 102 | } |
| 103 | |
| 104 | prefix := "error" |
| 105 | pc, _, _, ok := runtime.Caller(1) |
| 106 | details := runtime.FuncForPC(pc) |
| 107 | if ok && details != nil { |
| 108 | prefix = strings.ToLower(details.Name()) |
| 109 | if dotIdx := strings.LastIndex(prefix, "."); dotIdx > 0 { |
| 110 | prefix = prefix[dotIdx+1:] |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | if len(context) > 0 { |
| 115 | for i := range context { |
| 116 | context[i] = strings.TrimSpace(context[i]) |
| 117 | } |
| 118 | extra := strings.Join(context, ", ") |
| 119 | return fmt.Errorf("%s (%s): %w", prefix, extra, err) |
| 120 | } |
| 121 | |
| 122 | return fmt.Errorf("%s: %w", prefix, err) |
| 123 | } |