0
0
Fork 0
mirror of https://github.com/slackhq/nebula.git synced 2025-04-28 14:42:22 +00:00
slackhq_nebula/util/error.go
Wade Simmons 879852c32a
upgrade to yaml.v3 (#1148)
* upgrade to yaml.v3

The main nice fix here is that maps unmarshal into `map[string]any`
instead of `map[any]any`, so it cleans things up a bit.

* add config.AsBool

Since yaml.v3 doesn't automatically convert yes to bool now, for
backwards compat

* use type aliases for m

* more cleanup

* more cleanup

* more cleanup

* go mod cleanup
2025-03-31 16:08:34 -04:00

60 lines
1.4 KiB
Go

package util
import (
"errors"
"fmt"
"github.com/sirupsen/logrus"
)
type ContextualError struct {
RealError error
Fields map[string]any
Context string
}
func NewContextualError(msg string, fields map[string]any, realError error) *ContextualError {
return &ContextualError{Context: msg, Fields: fields, RealError: realError}
}
// ContextualizeIfNeeded is a helper function to turn an error into a ContextualError if it is not already one
func ContextualizeIfNeeded(msg string, err error) error {
switch err.(type) {
case *ContextualError:
return err
default:
return NewContextualError(msg, nil, err)
}
}
// LogWithContextIfNeeded is a helper function to log an error line for an error or ContextualError
func LogWithContextIfNeeded(msg string, err error, l *logrus.Logger) {
switch v := err.(type) {
case *ContextualError:
v.Log(l)
default:
l.WithError(err).Error(msg)
}
}
func (ce *ContextualError) Error() string {
if ce.RealError == nil {
return ce.Context
}
return fmt.Errorf("%s (%v): %w", ce.Context, ce.Fields, ce.RealError).Error()
}
func (ce *ContextualError) Unwrap() error {
if ce.RealError == nil {
return errors.New(ce.Context)
}
return ce.RealError
}
func (ce *ContextualError) Log(lr *logrus.Logger) {
if ce.RealError != nil {
lr.WithFields(ce.Fields).WithError(ce.RealError).Error(ce.Context)
} else {
lr.WithFields(ce.Fields).Error(ce.Context)
}
}