| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package semconv // import "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"reflect" |
| 9 |
|
| 10 |
"go.opentelemetry.io/otel/attribute" |
| 11 |
) |
| 12 |
|
| 13 |
// ErrorType returns an [attribute.KeyValue] identifying the error type of err. |
| 14 |
// |
| 15 |
// If err is nil, the returned attribute has the default value |
| 16 |
// [ErrorTypeOther]. |
| 17 |
// |
| 18 |
// If err or one of the errors in its chain has the method |
| 19 |
// |
| 20 |
// ErrorType() string |
| 21 |
// |
| 22 |
// the returned attribute has that method's return value. If multiple errors in |
| 23 |
// the chain implement this method, the value from the first match found by |
| 24 |
// [errors.As] is used. Otherwise, the returned attribute has a value derived |
| 25 |
// from the concrete type of err. |
| 26 |
// |
| 27 |
// The key of the returned attribute is [ErrorTypeKey]. |
| 28 |
func ErrorType(err error) attribute.KeyValue { |
| 29 |
if err == nil { |
| 30 |
return ErrorTypeOther |
| 31 |
} |
| 32 |
|
| 33 |
return ErrorTypeKey.String(errorType(err)) |
| 34 |
} |
| 35 |
|
| 36 |
func errorType(err error) string { |
| 37 |
var s string |
| 38 |
if et, ok := err.(interface{ ErrorType() string }); ok { |
| 39 |
// Fast path: check the top-level error first. |
| 40 |
s = et.ErrorType() |
| 41 |
} else { |
| 42 |
// Fallback: search the error chain for an ErrorType method. |
| 43 |
var et interface{ ErrorType() string } |
| 44 |
if errors.As(err, &et) { |
| 45 |
// Prioritize the ErrorType method if available. |
| 46 |
s = et.ErrorType() |
| 47 |
} |
| 48 |
} |
| 49 |
if s == "" { |
| 50 |
// Fallback to reflection if the ErrorType method is not supported or |
| 51 |
// returns an empty value. |
| 52 |
|
| 53 |
t := reflect.TypeOf(err) |
| 54 |
pkg, name := t.PkgPath(), t.Name() |
| 55 |
if pkg != "" && name != "" { |
| 56 |
s = pkg + "." + name |
| 57 |
} else { |
| 58 |
// The type has no package path or name (predeclared, not-defined, |
| 59 |
// or alias for a not-defined type). |
| 60 |
// |
| 61 |
// This is not guaranteed to be unique, but is a best effort. |
| 62 |
s = t.String() |
| 63 |
} |
| 64 |
} |
| 65 |
return s |
| 66 |
} |