codes.go

  1/*
  2 *
  3 * Copyright 2014 gRPC authors.
  4 *
  5 * Licensed under the Apache License, Version 2.0 (the "License");
  6 * you may not use this file except in compliance with the License.
  7 * You may obtain a copy of the License at
  8 *
  9 *     http://www.apache.org/licenses/LICENSE-2.0
 10 *
 11 * Unless required by applicable law or agreed to in writing, software
 12 * distributed under the License is distributed on an "AS IS" BASIS,
 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14 * See the License for the specific language governing permissions and
 15 * limitations under the License.
 16 *
 17 */
 18
 19// Package codes defines the canonical error codes used by gRPC. It is
 20// consistent across various languages.
 21package codes // import "google.golang.org/grpc/codes"
 22
 23import (
 24	"fmt"
 25	"strconv"
 26)
 27
 28// A Code is a status code defined according to the [gRPC documentation].
 29//
 30// Only the codes defined as consts in this package are valid codes. Do not use
 31// other code values.  Behavior of other codes is implementation-specific and
 32// interoperability between implementations is not guaranteed.
 33//
 34// [gRPC documentation]: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
 35type Code uint32
 36
 37const (
 38	// OK is returned on success.
 39	OK Code = 0
 40
 41	// Canceled indicates the operation was canceled (typically by the caller).
 42	//
 43	// The gRPC framework will generate this error code when cancellation
 44	// is requested.
 45	Canceled Code = 1
 46
 47	// Unknown error. An example of where this error may be returned is
 48	// if a Status value received from another address space belongs to
 49	// an error-space that is not known in this address space. Also
 50	// errors raised by APIs that do not return enough error information
 51	// may be converted to this error.
 52	//
 53	// The gRPC framework will generate this error code in the above two
 54	// mentioned cases.
 55	Unknown Code = 2
 56
 57	// InvalidArgument indicates client specified an invalid argument.
 58	// Note that this differs from FailedPrecondition. It indicates arguments
 59	// that are problematic regardless of the state of the system
 60	// (e.g., a malformed file name).
 61	//
 62	// This error code will not be generated by the gRPC framework.
 63	InvalidArgument Code = 3
 64
 65	// DeadlineExceeded means operation expired before completion.
 66	// For operations that change the state of the system, this error may be
 67	// returned even if the operation has completed successfully. For
 68	// example, a successful response from a server could have been delayed
 69	// long enough for the deadline to expire.
 70	//
 71	// The gRPC framework will generate this error code when the deadline is
 72	// exceeded.
 73	DeadlineExceeded Code = 4
 74
 75	// NotFound means some requested entity (e.g., file or directory) was
 76	// not found.
 77	//
 78	// This error code will not be generated by the gRPC framework.
 79	NotFound Code = 5
 80
 81	// AlreadyExists means an attempt to create an entity failed because one
 82	// already exists.
 83	//
 84	// This error code will not be generated by the gRPC framework.
 85	AlreadyExists Code = 6
 86
 87	// PermissionDenied indicates the caller does not have permission to
 88	// execute the specified operation. It must not be used for rejections
 89	// caused by exhausting some resource (use ResourceExhausted
 90	// instead for those errors). It must not be
 91	// used if the caller cannot be identified (use Unauthenticated
 92	// instead for those errors).
 93	//
 94	// This error code will not be generated by the gRPC core framework,
 95	// but expect authentication middleware to use it.
 96	PermissionDenied Code = 7
 97
 98	// ResourceExhausted indicates some resource has been exhausted, perhaps
 99	// a per-user quota, or perhaps the entire file system is out of space.
100	//
101	// This error code will be generated by the gRPC framework in
102	// out-of-memory and server overload situations, or when a message is
103	// larger than the configured maximum size.
104	ResourceExhausted Code = 8
105
106	// FailedPrecondition indicates operation was rejected because the
107	// system is not in a state required for the operation's execution.
108	// For example, directory to be deleted may be non-empty, an rmdir
109	// operation is applied to a non-directory, etc.
110	//
111	// A litmus test that may help a service implementor in deciding
112	// between FailedPrecondition, Aborted, and Unavailable:
113	//  (a) Use Unavailable if the client can retry just the failing call.
114	//  (b) Use Aborted if the client should retry at a higher-level
115	//      (e.g., restarting a read-modify-write sequence).
116	//  (c) Use FailedPrecondition if the client should not retry until
117	//      the system state has been explicitly fixed. E.g., if an "rmdir"
118	//      fails because the directory is non-empty, FailedPrecondition
119	//      should be returned since the client should not retry unless
120	//      they have first fixed up the directory by deleting files from it.
121	//  (d) Use FailedPrecondition if the client performs conditional
122	//      REST Get/Update/Delete on a resource and the resource on the
123	//      server does not match the condition. E.g., conflicting
124	//      read-modify-write on the same resource.
125	//
126	// This error code will not be generated by the gRPC framework.
127	FailedPrecondition Code = 9
128
129	// Aborted indicates the operation was aborted, typically due to a
130	// concurrency issue like sequencer check failures, transaction aborts,
131	// etc.
132	//
133	// See litmus test above for deciding between FailedPrecondition,
134	// Aborted, and Unavailable.
135	//
136	// This error code will not be generated by the gRPC framework.
137	Aborted Code = 10
138
139	// OutOfRange means operation was attempted past the valid range.
140	// E.g., seeking or reading past end of file.
141	//
142	// Unlike InvalidArgument, this error indicates a problem that may
143	// be fixed if the system state changes. For example, a 32-bit file
144	// system will generate InvalidArgument if asked to read at an
145	// offset that is not in the range [0,2^32-1], but it will generate
146	// OutOfRange if asked to read from an offset past the current
147	// file size.
148	//
149	// There is a fair bit of overlap between FailedPrecondition and
150	// OutOfRange. We recommend using OutOfRange (the more specific
151	// error) when it applies so that callers who are iterating through
152	// a space can easily look for an OutOfRange error to detect when
153	// they are done.
154	//
155	// This error code will not be generated by the gRPC framework.
156	OutOfRange Code = 11
157
158	// Unimplemented indicates operation is not implemented or not
159	// supported/enabled in this service.
160	//
161	// This error code will be generated by the gRPC framework. Most
162	// commonly, you will see this error code when a method implementation
163	// is missing on the server. It can also be generated for unknown
164	// compression algorithms or a disagreement as to whether an RPC should
165	// be streaming.
166	Unimplemented Code = 12
167
168	// Internal errors. Means some invariants expected by underlying
169	// system has been broken. If you see one of these errors,
170	// something is very broken.
171	//
172	// This error code will be generated by the gRPC framework in several
173	// internal error conditions.
174	Internal Code = 13
175
176	// Unavailable indicates the service is currently unavailable.
177	// This is a most likely a transient condition and may be corrected
178	// by retrying with a backoff. Note that it is not always safe to retry
179	// non-idempotent operations.
180	//
181	// See litmus test above for deciding between FailedPrecondition,
182	// Aborted, and Unavailable.
183	//
184	// This error code will be generated by the gRPC framework during
185	// abrupt shutdown of a server process or network connection.
186	Unavailable Code = 14
187
188	// DataLoss indicates unrecoverable data loss or corruption.
189	//
190	// This error code will not be generated by the gRPC framework.
191	DataLoss Code = 15
192
193	// Unauthenticated indicates the request does not have valid
194	// authentication credentials for the operation.
195	//
196	// The gRPC framework will generate this error code when the
197	// authentication metadata is invalid or a Credentials callback fails,
198	// but also expect authentication middleware to generate it.
199	Unauthenticated Code = 16
200
201	_maxCode = 17
202)
203
204var strToCode = map[string]Code{
205	`"OK"`: OK,
206	`"CANCELLED"`:/* [sic] */ Canceled,
207	`"UNKNOWN"`:             Unknown,
208	`"INVALID_ARGUMENT"`:    InvalidArgument,
209	`"DEADLINE_EXCEEDED"`:   DeadlineExceeded,
210	`"NOT_FOUND"`:           NotFound,
211	`"ALREADY_EXISTS"`:      AlreadyExists,
212	`"PERMISSION_DENIED"`:   PermissionDenied,
213	`"RESOURCE_EXHAUSTED"`:  ResourceExhausted,
214	`"FAILED_PRECONDITION"`: FailedPrecondition,
215	`"ABORTED"`:             Aborted,
216	`"OUT_OF_RANGE"`:        OutOfRange,
217	`"UNIMPLEMENTED"`:       Unimplemented,
218	`"INTERNAL"`:            Internal,
219	`"UNAVAILABLE"`:         Unavailable,
220	`"DATA_LOSS"`:           DataLoss,
221	`"UNAUTHENTICATED"`:     Unauthenticated,
222}
223
224// UnmarshalJSON unmarshals b into the Code.
225func (c *Code) UnmarshalJSON(b []byte) error {
226	// From json.Unmarshaler: By convention, to approximate the behavior of
227	// Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as
228	// a no-op.
229	if string(b) == "null" {
230		return nil
231	}
232	if c == nil {
233		return fmt.Errorf("nil receiver passed to UnmarshalJSON")
234	}
235
236	if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil {
237		if ci >= _maxCode {
238			return fmt.Errorf("invalid code: %d", ci)
239		}
240
241		*c = Code(ci)
242		return nil
243	}
244
245	if jc, ok := strToCode[string(b)]; ok {
246		*c = jc
247		return nil
248	}
249	return fmt.Errorf("invalid code: %q", string(b))
250}