blob: 28393a544007010275b9cd833172bfe6b6d47277 [file] [log] [blame]
Joey Armstrong5f51f2e2023-01-17 17:06:26 -05001// Copyright The OpenTelemetry Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package codes defines the canonical error codes used by OpenTelemetry.
16//
17// It conforms to [the OpenTelemetry
18// specification](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/api.md#statuscanonicalcode).
19package codes // import "go.opentelemetry.io/otel/codes"
20
21import (
22 "fmt"
23 "strconv"
24)
25
26const (
27 // Unset is the default status code.
28 Unset Code = 0
29 // Error indicates the operation contains an error.
30 Error Code = 1
31 // Ok indicates operation has been validated by an Application developers
32 // or Operator to have completed successfully, or contain no error.
33 Ok Code = 2
34
35 maxCode = 3
36)
37
38// Code is an 32-bit representation of a status state.
39type Code uint32
40
41var codeToStr = map[Code]string{
42 Unset: "Unset",
43 Error: "Error",
44 Ok: "Ok",
45}
46
47var strToCode = map[string]Code{
48 "Unset": Unset,
49 "Error": Error,
50 "Ok": Ok,
51}
52
53// String returns the Code as a string.
54func (c Code) String() string {
55 return codeToStr[c]
56}
57
58// UnmarshalJSON unmarshals b into the Code.
59//
60// This is based on the functionality in the gRPC codes package:
61// https://github.com/grpc/grpc-go/blob/bb64fee312b46ebee26be43364a7a966033521b1/codes/codes.go#L218-L244
62func (c *Code) UnmarshalJSON(b []byte) error {
63 // From json.Unmarshaler: By convention, to approximate the behavior of
64 // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as
65 // a no-op.
66 if string(b) == "null" {
67 return nil
68 }
69 if c == nil {
70 return fmt.Errorf("nil receiver passed to UnmarshalJSON")
71 }
72
73 if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil {
74 if ci >= maxCode {
75 return fmt.Errorf("invalid code: %q", ci)
76 }
77
78 *c = Code(ci)
79 return nil
80 }
81
82 if jc, ok := strToCode[string(b)]; ok {
83 *c = jc
84 return nil
85 }
86 return fmt.Errorf("invalid code: %q", string(b))
87}
88
89// MarshalJSON returns c as the JSON encoding of c.
90func (c *Code) MarshalJSON() ([]byte, error) {
91 if c == nil {
92 return []byte("null"), nil
93 }
94 str, ok := codeToStr[*c]
95 if !ok {
96 return nil, fmt.Errorf("invalid code: %d", *c)
97 }
98 return []byte(fmt.Sprintf("%q", str)), nil
99}