2021-11-10 20:47:38 -07:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2024-01-31 13:31:46 -07:00
|
|
|
"fmt"
|
2021-11-10 20:47:38 -07:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ContextualError struct {
|
|
|
|
RealError error
|
|
|
|
Fields map[string]interface{}
|
|
|
|
Context string
|
|
|
|
}
|
|
|
|
|
2023-08-14 20:32:40 -06:00
|
|
|
func NewContextualError(msg string, fields map[string]interface{}, realError error) *ContextualError {
|
|
|
|
return &ContextualError{Context: msg, Fields: fields, RealError: realError}
|
2021-11-10 20:47:38 -07:00
|
|
|
}
|
|
|
|
|
2023-08-14 20:32:40 -06:00
|
|
|
// 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 {
|
2021-11-10 20:47:38 -07:00
|
|
|
if ce.RealError == nil {
|
|
|
|
return ce.Context
|
|
|
|
}
|
2024-01-31 13:31:46 -07:00
|
|
|
return fmt.Errorf("%s (%v): %w", ce.Context, ce.Fields, ce.RealError).Error()
|
2021-11-10 20:47:38 -07:00
|
|
|
}
|
|
|
|
|
2023-08-14 20:32:40 -06:00
|
|
|
func (ce *ContextualError) Unwrap() error {
|
2021-11-10 20:47:38 -07:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|