Files
threshold/internal/event/event_error.go
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

80 lines
2.2 KiB
Go
Raw Normal View History

2023-02-02 17:15:17 -08:00
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
2021-06-06 07:57:24 -04:00
package event
2021-06-22 16:23:27 -05:00
import (
"errors"
2021-06-22 16:23:27 -05:00
"fmt"
"reflect"
2021-06-22 16:23:27 -05:00
)
2021-06-06 07:57:24 -04:00
// errorVersion defines the version of error events
const errorVersion = "v0.1"
type err struct {
2022-10-25 18:29:38 -05:00
Error string `json:"error"`
ErrorFields error `json:"error_fields"`
Id Id `json:"id,omitempty"`
Version string `json:"version"`
Op Op `json:"op,omitempty"`
RequestInfo *RequestInfo `json:"request_info,omitempty"`
Info map[string]any `json:"info,omitempty"`
2021-06-06 07:57:24 -04:00
}
func newError(fromOperation Op, e error, opt ...Option) (*err, error) {
const op = "event.newError"
if fromOperation == "" {
2021-06-22 16:23:27 -05:00
return nil, fmt.Errorf("%s: missing operation: %w", op, ErrInvalidParameter)
2021-06-06 07:57:24 -04:00
}
if e == nil {
2021-06-22 16:23:27 -05:00
return nil, fmt.Errorf("%s: missing error: %w", op, ErrInvalidParameter)
2021-06-06 07:57:24 -04:00
}
opts := getOpts(opt...)
if opts.withId == "" {
var err error
opts.withId, err = NewId(string(ErrorType))
2021-06-06 07:57:24 -04:00
if err != nil {
2021-06-22 16:23:27 -05:00
return nil, fmt.Errorf("%s: %w", op, err)
2021-06-06 07:57:24 -04:00
}
}
// multierror doesn't support json Marshaling which will cause a problem
// when the event is formatted, so we're going to convert it here to a
// stdlib error
if reflect.TypeOf(e).String() == "*multierror.Error" {
e = errors.New(e.Error())
}
2021-06-06 07:57:24 -04:00
newErr := &err{
Id: Id(opts.withId),
Op: fromOperation,
Version: errorVersion,
RequestInfo: opts.withRequestInfo,
Info: opts.withInfo,
Error: e.Error(),
ErrorFields: e,
2021-06-06 07:57:24 -04:00
}
if err := newErr.validate(); err != nil {
2021-06-22 16:23:27 -05:00
return nil, fmt.Errorf("%s: %w", op, err)
2021-06-06 07:57:24 -04:00
}
return newErr, nil
}
// EventType is required for all event types by the eventlogger broker
func (e *err) EventType() string { return string(ErrorType) }
func (e *err) validate() error {
const op = "event.(err).validate"
if e.Id == "" {
2021-06-22 16:23:27 -05:00
return fmt.Errorf("%s: missing id: %w", op, ErrInvalidParameter)
2021-06-06 07:57:24 -04:00
}
if e.Op == "" {
2021-06-22 16:23:27 -05:00
return fmt.Errorf("%s: missing operation: %w", op, ErrInvalidParameter)
2021-06-06 07:57:24 -04:00
}
if e.ErrorFields == nil {
return fmt.Errorf("%s: missing error fields: %w", op, ErrInvalidParameter)
}
if e.Error == "" {
2021-06-22 16:23:27 -05:00
return fmt.Errorf("%s: missing error: %w", op, ErrInvalidParameter)
2021-06-06 07:57:24 -04:00
}
return nil
}