Debian Codegraph @

semconv/v1.37.0/error_type.go

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