/
error.go
82 lines (68 loc) · 2.09 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package errors // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/errors"
import (
"encoding/json"
"errors"
"fmt"
"go.uber.org/zap/zapcore"
)
// AgentError is an error that occurs in the agent.
type AgentError struct {
Description string
Suggestion string
Details ErrorDetails
}
// Error will return the error message.
func (e AgentError) Error() string {
if len(e.Details) == 0 {
return e.Description
}
marshaled, _ := json.Marshal(e.Details)
return fmt.Sprintf("%s: %s", e.Description, string(marshaled))
}
// MarshalLogObject will define the representation of this error when logging.
func (e AgentError) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddString("description", e.Description)
if e.Suggestion != "" {
encoder.AddString("suggestion", e.Suggestion)
}
if len(e.Details) != 0 {
_ = encoder.AddObject("details", e.Details)
}
return nil
}
// WithDetails will return the error with additional details
func (e AgentError) WithDetails(keyValues ...string) AgentError {
return WithDetails(e, keyValues...)
}
// WithDetails will add details to an agent error
func WithDetails(err error, keyValues ...string) AgentError {
var agentErr AgentError
if errors.As(err, &agentErr) {
if len(keyValues) > 0 {
for i := 0; i+1 < len(keyValues); i += 2 {
agentErr.Details[keyValues[i]] = keyValues[i+1]
}
}
return agentErr
}
return NewError(err.Error(), "", keyValues...)
}
// Wrap adds context to the description for richer logs
func Wrap(err error, context string) AgentError {
var agentErr AgentError
if errors.As(err, &agentErr) {
agentErr.Description = fmt.Sprintf("%s: %s", context, agentErr.Description)
return agentErr
}
return NewError(fmt.Sprintf("%s: %s", context, err.Error()), "")
}
// NewError will create a new agent error.
func NewError(description string, suggestion string, keyValues ...string) AgentError {
return AgentError{
Description: description,
Suggestion: suggestion,
Details: createDetails(keyValues),
}
}