blob: 8e1974c9259ec99a97a7be97b6b4dc9d9ae1e8c3 [file] [log] [blame]
Abseil Team914ff442020-02-20 12:34:37 -08001// Copyright 2019 The Abseil 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// https://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.
Abseil Team930fbec2020-09-02 08:15:12 -070014//
15// -----------------------------------------------------------------------------
16// File: status.h
17// -----------------------------------------------------------------------------
18//
19// This header file defines the Abseil `status` library, consisting of:
20//
21// * An `absl::Status` class for holding error handling information
22// * A set of canonical `absl::StatusCode` error codes, and associated
23// utilities for generating and propogating status codes.
24// * A set of helper functions for creating status codes and checking their
25// values
26//
27// Within Google, `absl::Status` is the primary mechanism for indicating
28// recoverable errors across API boundaries (and in particular across RPC
29// boundaries). Most functions which can produce a recoverable error should
30// be designed to return an `absl::Status` (or `absl::StatusOr`).
31//
32// Example:
33//
34// absl::Status myFunction(absl::string_view fname, ...) {
35// ...
36// // encounter error
37// if (error condition) {
38// return absl::InvalidArgumentError("bad mode");
39// }
40// // else, return OK
41// return absl::OkStatus();
42// }
43//
44// An `absl::Status` is designed to either return "OK" or one of a number of
45// different error codes, corresponding to typical error conditions.
46// In almost all cases, when using `absl::Status` you should use the canonical
47// error codes (of type `absl::StatusCode`) enumerated in this header file.
48// These canonical codes are understood across the codebase and will be
49// accepted across all API and RPC boundaries.
50//
51// An `absl::Status` can optionally include a payload with more information
52// about the error. Typically, this payload serves one of several purposes:
53//
54// * It may provide more fine-grained semantic information about the error to
55// facilitate actionable remedies.
56// * It may provide human-readable contexual information that is more
57// appropriate
58// to display to an end user.
59//
Abseil Team914ff442020-02-20 12:34:37 -080060#ifndef ABSL_STATUS_STATUS_H_
61#define ABSL_STATUS_STATUS_H_
62
63#include <iostream>
64#include <string>
65
66#include "absl/container/inlined_vector.h"
Abseil Teamc6b3f2c2020-08-13 14:05:00 -070067#include "absl/status/internal/status_internal.h"
Abseil Team914ff442020-02-20 12:34:37 -080068#include "absl/strings/cord.h"
69#include "absl/types/optional.h"
70
71namespace absl {
72ABSL_NAMESPACE_BEGIN
73
Abseil Team930fbec2020-09-02 08:15:12 -070074// absl::StatusCode
75//
76// An `absl::StatusCode` is an enumerated type indicating either no error ("OK")
77// or an error condition. In most cases, an `absl::Status` indicates a
78// recoverable error, and the purpose of signalling an error is to indicate what
79// action to take in response to that error. These error codes map to the proto
80// RPC error codes indicated in https://cloud.google.com/apis/design/errors.
81//
82// The errors listed below are the canonical errors associated with
83// `absl::Status` and are used throughout the codebase. As a result, these
84// error codes are somewhat generic.
85//
86// In general, try to return the most specific error that applies if more than
87// one error may pertain. For example, prefer `kOutOfRange` over
88// `kFailedPrecondition` if both codes apply. Similarly prefer `kNotFound` or
89// `kAlreadyExists` over `kFailedPrecondition`.
90//
91// Because these errors may travel RPC boundaries, these codes are tied to the
92// `google.rpc.Code` definitions within
93// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
94// The string value of these RPC codes is denoted within each enum below.
95//
96// If your error handling code requires more context, you can attach payloads
97// to your status. See `absl::Status::SetPayload()` and
98// `absl::Status::GetPayload()` below.
Abseil Team914ff442020-02-20 12:34:37 -080099enum class StatusCode : int {
Abseil Team930fbec2020-09-02 08:15:12 -0700100 // StatusCode::kOk
101 //
102 // kOK (gRPC code "OK") does not indicate an error; this value is returned on
103 // success. It is typical to check for this value before proceeding on any
104 // given call across an API or RPC boundary. To check this value, use the
105 // `absl::Status::ok()` member function rather than inspecting the raw code.
Abseil Team914ff442020-02-20 12:34:37 -0800106 kOk = 0,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700107
Abseil Team930fbec2020-09-02 08:15:12 -0700108 // StatusCode::kCancelled
109 //
110 // kCanelled (gRPC code "CANCELLED") indicates the operation was cancelled,
111 // typically by the caller.
Abseil Team914ff442020-02-20 12:34:37 -0800112 kCancelled = 1,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700113
Abseil Team930fbec2020-09-02 08:15:12 -0700114 // StatusCode::kUnknown
115 //
116 // kUnknown (gRPC code "UNKNOWN") indicates an unknown error occurred. In
117 // general, more specific errors should be raised, if possible. Errors raised
118 // by APIs that do not return enough error information may be converted to
119 // this error.
Abseil Team914ff442020-02-20 12:34:37 -0800120 kUnknown = 2,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700121
Abseil Team930fbec2020-09-02 08:15:12 -0700122 // StatusCode::kInvalidArgument
123 //
124 // kInvalidArgument (gRPC code "INVALID_ARGUMENT") indicates the caller
125 // specified an invalid argument, such a malformed filename. Note that such
126 // errors should be narrowly limited to indicate to the invalid nature of the
127 // arguments themselves. Errors with validly formed arguments that may cause
128 // errors with the state of the receiving system should be denoted with
129 // `kFailedPrecondition` instead.
Abseil Team914ff442020-02-20 12:34:37 -0800130 kInvalidArgument = 3,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700131
Abseil Team930fbec2020-09-02 08:15:12 -0700132 // StatusCode::kDeadlineExceeded
133 //
134 // kDeadlineExceeded (gRPC code "DEADLINE_EXCEEDED") indicates a deadline
135 // expired before the operation could complete. For operations that may change
136 // state within a system, this error may be returned even if the operation has
137 // completed successfully. For example, a successful response from a server
138 // could have been delayed long enough for the deadline to expire.
Abseil Team914ff442020-02-20 12:34:37 -0800139 kDeadlineExceeded = 4,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700140
Abseil Team930fbec2020-09-02 08:15:12 -0700141 // StatusCode::kNotFound
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700142 //
Abseil Team930fbec2020-09-02 08:15:12 -0700143 // kNotFound (gRPC code "NOT_FOUND") indicates some requested entity (such as
144 // a file or directory) was not found.
145 //
146 // `kNotFound` is useful if a request should be denied for an entire class of
147 // users, such as during a gradual feature rollout or undocumented allow list.
148 // If, instead, a request should be denied for specific sets of users, such as
149 // through user-based access control, use `kPermissionDenied` instead.
Abseil Team914ff442020-02-20 12:34:37 -0800150 kNotFound = 5,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700151
Abseil Team930fbec2020-09-02 08:15:12 -0700152 // StatusCode::kAlreadyExists
153 //
154 // kAlreadyExists (gRPC code "ALREADY_EXISTS") indicates the entity that a
155 // caller attempted to create (such as file or directory) is already present.
Abseil Team914ff442020-02-20 12:34:37 -0800156 kAlreadyExists = 6,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700157
Abseil Team930fbec2020-09-02 08:15:12 -0700158 // StatusCode::kPermissionDenied
159 //
160 // kPermissionDenied (gRPC code "PERMISSION_DENIED") indicates that the caller
161 // does not have permission to execute the specified operation. Note that this
162 // error is different than an error due to an *un*authenticated user. This
163 // error code does not imply the request is valid or the requested entity
164 // exists or satisfies any other pre-conditions.
165 //
166 // `kPermissionDenied` must not be used for rejections caused by exhausting
167 // some resource. Instead, use `kResourceExhausted` for those errors.
168 // `kPermissionDenied` must not be used if the caller cannot be identified.
169 // Instead, use `kUnauthenticated` for those errors.
Abseil Team914ff442020-02-20 12:34:37 -0800170 kPermissionDenied = 7,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700171
Abseil Team930fbec2020-09-02 08:15:12 -0700172 // StatusCode::kResourceExhausted
173 //
174 // kResourceExhausted (gRPC code "RESOURCE_EXHAUSTED") indicates some resource
175 // has been exhausted, perhaps a per-user quota, or perhaps the entire file
176 // system is out of space.
Abseil Team914ff442020-02-20 12:34:37 -0800177 kResourceExhausted = 8,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700178
Abseil Team930fbec2020-09-02 08:15:12 -0700179 // StatusCode::kFailedPrecondition
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700180 //
Abseil Team930fbec2020-09-02 08:15:12 -0700181 // kFailedPrecondition (gRPC code "FAILED_PRECONDITION") indicates that the
182 // operation was rejected because the system is not in a state required for
183 // the operation's execution. For example, a directory to be deleted may be
184 // non-empty, an "rmdir" operation is applied to a non-directory, etc.
185 //
186 // Some guidelines that may help a service implementer in deciding between
187 // `kFailedPrecondition`, `kAborted`, and `kUnavailable`:
188 //
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700189 // (a) Use `kUnavailable` if the client can retry just the failing call.
Abseil Team930fbec2020-09-02 08:15:12 -0700190 // (b) Use `kAborted` if the client should retry at a higher transaction
191 // level (such as when a client-specified test-and-set fails, indicating
192 // the client should restart a read-modify-write sequence).
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700193 // (c) Use `kFailedPrecondition` if the client should not retry until
194 // the system state has been explicitly fixed. For example, if an "rmdir"
195 // fails because the directory is non-empty, `kFailedPrecondition`
196 // should be returned since the client should not retry unless
197 // the files are deleted from the directory.
Abseil Team914ff442020-02-20 12:34:37 -0800198 kFailedPrecondition = 9,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700199
Abseil Team930fbec2020-09-02 08:15:12 -0700200 // StatusCode::kAborted
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700201 //
Abseil Team930fbec2020-09-02 08:15:12 -0700202 // kAborted (gRPC code "ABORTED") indicates the operation was aborted,
203 // typically due to a concurrency issue such as a sequencer check failure or a
204 // failed transaction.
205 //
206 // See the guidelines above for deciding between `kFailedPrecondition`,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700207 // `kAborted`, and `kUnavailable`.
Abseil Team914ff442020-02-20 12:34:37 -0800208 kAborted = 10,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700209
Abseil Team930fbec2020-09-02 08:15:12 -0700210 // StatusCode::kOutofRange
211 //
212 // kOutofRange (gRPC code "OUT_OF_RANGE") indicates the operation was
213 // attempted past the valid range, such as seeking or reading past an
214 // end-of-file.
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700215 //
216 // Unlike `kInvalidArgument`, this error indicates a problem that may
217 // be fixed if the system state changes. For example, a 32-bit file
218 // system will generate `kInvalidArgument` if asked to read at an
219 // offset that is not in the range [0,2^32-1], but it will generate
220 // `kOutOfRange` if asked to read from an offset past the current
221 // file size.
222 //
223 // There is a fair bit of overlap between `kFailedPrecondition` and
224 // `kOutOfRange`. We recommend using `kOutOfRange` (the more specific
225 // error) when it applies so that callers who are iterating through
226 // a space can easily look for an `kOutOfRange` error to detect when
227 // they are done.
Abseil Team914ff442020-02-20 12:34:37 -0800228 kOutOfRange = 11,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700229
Abseil Team930fbec2020-09-02 08:15:12 -0700230 // StatusCode::kUnimplemented
231 //
232 // kUnimplemented (gRPC code "UNIMPLEMENTED") indicates the operation is not
233 // implemented or supported in this service. In this case, the operation
234 // should not be re-attempted.
Abseil Team914ff442020-02-20 12:34:37 -0800235 kUnimplemented = 12,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700236
Abseil Team930fbec2020-09-02 08:15:12 -0700237 // StatusCode::kInternal
238 //
239 // kInternal (gRPC code "INTERNAL") indicates an internal error has occurred
240 // and some invariants expected by the underlying system have not been
241 // satisfied. This error code is reserved for serious errors.
Abseil Team914ff442020-02-20 12:34:37 -0800242 kInternal = 13,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700243
Abseil Team930fbec2020-09-02 08:15:12 -0700244 // StatusCode::kUnavailable
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700245 //
Abseil Team930fbec2020-09-02 08:15:12 -0700246 // kUnavailable (gRPC code "UNAVAILABLE") indicates the service is currently
247 // unavailable and that this is most likely a transient condition. An error
248 // such as this can be corrected by retrying with a backoff scheme. Note that
249 // it is not always safe to retry non-idempotent operations.
250 //
251 // See the guidelines above for deciding between `kFailedPrecondition`,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700252 // `kAborted`, and `kUnavailable`.
Abseil Team914ff442020-02-20 12:34:37 -0800253 kUnavailable = 14,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700254
Abseil Team930fbec2020-09-02 08:15:12 -0700255 // StatusCode::kDataLoss
256 //
257 // kDataLoss (gRPC code "DATA_LOSS") indicates that unrecoverable data loss or
258 // corruption has occurred. As this error is serious, proper alerting should
259 // be attached to errors such as this.
Abseil Team914ff442020-02-20 12:34:37 -0800260 kDataLoss = 15,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700261
Abseil Team930fbec2020-09-02 08:15:12 -0700262 // StatusCode::kUnauthenticated
263 //
264 // kUnauthenticated (gRPC code "UNAUTHENTICATED") indicates that the request
265 // does not have valid authentication credentials for the operation. Correct
266 // the authentication and try again.
Abseil Team914ff442020-02-20 12:34:37 -0800267 kUnauthenticated = 16,
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700268
Abseil Team930fbec2020-09-02 08:15:12 -0700269 // StatusCode::DoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700270 //
Abseil Team930fbec2020-09-02 08:15:12 -0700271 // NOTE: this error code entry should not be used and you should not rely on
272 // its value, which may change.
Abseil Teamd39fe6c2020-07-27 12:21:58 -0700273 //
Abseil Team930fbec2020-09-02 08:15:12 -0700274 // The purpose of this enumerated value is to force people who handle status
275 // codes with `switch()` statements to *not* simply enumerate all possible
276 // values, but instead provide a "default:" case. Providing such a default
277 // case ensures that code will compile when new codes are added.
Abseil Team914ff442020-02-20 12:34:37 -0800278 kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20
279};
280
Abseil Team930fbec2020-09-02 08:15:12 -0700281// StatusCodeToString()
282//
Abseil Team914ff442020-02-20 12:34:37 -0800283// Returns the name for the status code, or "" if it is an unknown value.
284std::string StatusCodeToString(StatusCode code);
285
Abseil Team930fbec2020-09-02 08:15:12 -0700286// operator<<
287//
Abseil Team914ff442020-02-20 12:34:37 -0800288// Streams StatusCodeToString(code) to `os`.
289std::ostream& operator<<(std::ostream& os, StatusCode code);
290
Abseil Team930fbec2020-09-02 08:15:12 -0700291// absl::Status
292//
Abseil Team914ff442020-02-20 12:34:37 -0800293class ABSL_MUST_USE_RESULT Status final {
294 public:
Abseil Team930fbec2020-09-02 08:15:12 -0700295 // Constructors
296
Abseil Team914ff442020-02-20 12:34:37 -0800297 // Creates an OK status with no message or payload.
298 Status();
299
300 // Create a status in the canonical error space with the specified code and
Abseil Teamcde2e242020-04-24 06:12:31 -0700301 // error message. If `code == absl::StatusCode::kOk`, `msg` is ignored and an
Abseil Team914ff442020-02-20 12:34:37 -0800302 // object identical to an OK status is constructed.
303 //
304 // `msg` must be in UTF-8. The implementation may complain (e.g.,
305 // by printing a warning) if it is not.
306 Status(absl::StatusCode code, absl::string_view msg);
307
308 Status(const Status&);
309 Status& operator=(const Status& x);
310
Abseil Team930fbec2020-09-02 08:15:12 -0700311 // Move operators
312
Abseil Team914ff442020-02-20 12:34:37 -0800313 // The moved-from state is valid but unspecified.
314 Status(Status&&) noexcept;
315 Status& operator=(Status&&);
316
317 ~Status();
318
Abseil Team930fbec2020-09-02 08:15:12 -0700319 // Status::Update()
320 //
Abseil Team914ff442020-02-20 12:34:37 -0800321 // If `this->ok()`, stores `new_status` into *this. If `!this->ok()`,
322 // preserves the current data. May, in the future, augment the current status
323 // with additional information about `new_status`.
324 //
325 // Convenient way of keeping track of the first error encountered.
326 // Instead of:
327 // if (overall_status.ok()) overall_status = new_status
328 // Use:
329 // overall_status.Update(new_status);
330 //
331 // Style guide exception for rvalue reference granted in CL 153567220.
332 void Update(const Status& new_status);
333 void Update(Status&& new_status);
334
Abseil Team930fbec2020-09-02 08:15:12 -0700335 // Status::ok()
336 //
Abseil Team914ff442020-02-20 12:34:37 -0800337 // Returns true if the Status is OK.
338 ABSL_MUST_USE_RESULT bool ok() const;
339
Abseil Team930fbec2020-09-02 08:15:12 -0700340 // Status::code()
341 //
Abseil Team914ff442020-02-20 12:34:37 -0800342 // Returns the (canonical) error code.
343 absl::StatusCode code() const;
344
Abseil Team930fbec2020-09-02 08:15:12 -0700345 // Status::raw_code()
346 //
Abseil Team914ff442020-02-20 12:34:37 -0800347 // Returns the raw (canonical) error code which could be out of the range of
348 // the local `absl::StatusCode` enum. NOTE: This should only be called when
349 // converting to wire format. Use `code` for error handling.
350 int raw_code() const;
351
Abseil Team930fbec2020-09-02 08:15:12 -0700352 // Status::message()
353 //
Abseil Team914ff442020-02-20 12:34:37 -0800354 // Returns the error message. Note: prefer ToString() for debug logging.
355 // This message rarely describes the error code. It is not unusual for the
Abseil Teama877af12020-03-10 09:28:06 -0700356 // error message to be the empty string.
Abseil Team914ff442020-02-20 12:34:37 -0800357 absl::string_view message() const;
358
359 friend bool operator==(const Status&, const Status&);
360 friend bool operator!=(const Status&, const Status&);
361
Abseil Team930fbec2020-09-02 08:15:12 -0700362 // Status::ToString()
363 //
Abseil Team914ff442020-02-20 12:34:37 -0800364 // Returns a combination of the error code name, the message and the payloads.
365 // You can expect the code name and the message to be substrings of the
366 // result, and the payloads to be printed by the registered printer extensions
367 // if they are recognized.
368 // WARNING: Do not depend on the exact format of the result of `ToString()`
369 // which is subject to change.
370 std::string ToString() const;
371
Abseil Team930fbec2020-09-02 08:15:12 -0700372 // Status::IgnoreError()
373 //
Abseil Team914ff442020-02-20 12:34:37 -0800374 // Ignores any errors. This method does nothing except potentially suppress
375 // complaints from any tools that are checking that errors are not dropped on
376 // the floor.
377 void IgnoreError() const;
378
Abseil Team930fbec2020-09-02 08:15:12 -0700379 // swap()
380 //
Abseil Team914ff442020-02-20 12:34:37 -0800381 // Swap the contents of `a` with `b`
382 friend void swap(Status& a, Status& b);
383
Abseil Team930fbec2020-09-02 08:15:12 -0700384 //----------------------------------------------------------------------------
Abseil Team914ff442020-02-20 12:34:37 -0800385 // Payload management APIs
Abseil Team930fbec2020-09-02 08:15:12 -0700386 //----------------------------------------------------------------------------
Abseil Team914ff442020-02-20 12:34:37 -0800387
388 // Type URL should be unique and follow the naming convention below:
389 // The idea of type URL comes from `google.protobuf.Any`
390 // (https://developers.google.com/protocol-buffers/docs/proto3#any). The
391 // type URL should be globally unique and follow the format of URL
392 // (https://en.wikipedia.org/wiki/URL). The default type URL for a given
393 // protobuf message type is "type.googleapis.com/packagename.messagename". For
394 // other custom wire formats, users should define the format of type URL in a
395 // similar practice so as to minimize the chance of conflict between type
396 // URLs. Users should make sure that the type URL can be mapped to a concrete
397 // C++ type if they want to deserialize the payload and read it effectively.
398
Abseil Team930fbec2020-09-02 08:15:12 -0700399 // Status::GetPayload()
400 //
Abseil Team914ff442020-02-20 12:34:37 -0800401 // Gets the payload based for `type_url` key, if it is present.
402 absl::optional<absl::Cord> GetPayload(absl::string_view type_url) const;
403
Abseil Team930fbec2020-09-02 08:15:12 -0700404 // Status::SetPayload()
405 //
Abseil Team914ff442020-02-20 12:34:37 -0800406 // Sets the payload for `type_url` key for a non-ok status, overwriting any
407 // existing payload for `type_url`.
408 //
409 // NOTE: Does nothing if the Status is ok.
410 void SetPayload(absl::string_view type_url, absl::Cord payload);
411
Abseil Team930fbec2020-09-02 08:15:12 -0700412 // Status::ErasePayload()
413 //
Abseil Team914ff442020-02-20 12:34:37 -0800414 // Erases the payload corresponding to the `type_url` key. Returns true if
415 // the payload was present.
416 bool ErasePayload(absl::string_view type_url);
417
Abseil Team930fbec2020-09-02 08:15:12 -0700418 // Status::ForEachPayload()
419 //
Abseil Team914ff442020-02-20 12:34:37 -0800420 // Iterates over the stored payloads and calls `visitor(type_key, payload)`
421 // for each one.
422 //
423 // NOTE: The order of calls to `visitor` is not specified and may change at
424 // any time.
425 //
426 // NOTE: Any mutation on the same 'Status' object during visitation is
427 // forbidden and could result in undefined behavior.
428 void ForEachPayload(
429 const std::function<void(absl::string_view, const absl::Cord&)>& visitor)
430 const;
431
432 private:
433 friend Status CancelledError();
434
435 // Creates a status in the canonical error space with the specified
436 // code, and an empty error message.
437 explicit Status(absl::StatusCode code);
438
439 static void UnrefNonInlined(uintptr_t rep);
440 static void Ref(uintptr_t rep);
441 static void Unref(uintptr_t rep);
442
443 // REQUIRES: !ok()
444 // Ensures rep_ is not shared with any other Status.
445 void PrepareToModify();
446
447 const status_internal::Payloads* GetPayloads() const;
448 status_internal::Payloads* GetPayloads();
449
450 // Takes ownership of payload.
451 static uintptr_t NewRep(absl::StatusCode code, absl::string_view msg,
452 std::unique_ptr<status_internal::Payloads> payload);
453 static bool EqualsSlow(const absl::Status& a, const absl::Status& b);
454
455 // MSVC 14.0 limitation requires the const.
456 static constexpr const char kMovedFromString[] =
457 "Status accessed after move.";
458
459 static const std::string* EmptyString();
460 static const std::string* MovedFromString();
461
462 // Returns whether rep contains an inlined representation.
463 // See rep_ for details.
464 static bool IsInlined(uintptr_t rep);
465
466 // Indicates whether this Status was the rhs of a move operation. See rep_
467 // for details.
468 static bool IsMovedFrom(uintptr_t rep);
469 static uintptr_t MovedFromRep();
470
471 // Convert between error::Code and the inlined uintptr_t representation used
472 // by rep_. See rep_ for details.
473 static uintptr_t CodeToInlinedRep(absl::StatusCode code);
474 static absl::StatusCode InlinedRepToCode(uintptr_t rep);
475
476 // Converts between StatusRep* and the external uintptr_t representation used
477 // by rep_. See rep_ for details.
478 static uintptr_t PointerToRep(status_internal::StatusRep* r);
479 static status_internal::StatusRep* RepToPointer(uintptr_t r);
480
Abseil Teama877af12020-03-10 09:28:06 -0700481 // Returns string for non-ok Status.
Abseil Team914ff442020-02-20 12:34:37 -0800482 std::string ToStringSlow() const;
483
484 // Status supports two different representations.
485 // - When the low bit is off it is an inlined representation.
486 // It uses the canonical error space, no message or payload.
487 // The error code is (rep_ >> 2).
488 // The (rep_ & 2) bit is the "moved from" indicator, used in IsMovedFrom().
489 // - When the low bit is on it is an external representation.
490 // In this case all the data comes from a heap allocated Rep object.
491 // (rep_ - 1) is a status_internal::StatusRep* pointer to that structure.
492 uintptr_t rep_;
493};
494
Abseil Team930fbec2020-09-02 08:15:12 -0700495// OkStatus()
496//
Abseil Team914ff442020-02-20 12:34:37 -0800497// Returns an OK status, equivalent to a default constructed instance.
498Status OkStatus();
499
Abseil Team930fbec2020-09-02 08:15:12 -0700500// operator<<()
501//
Abseil Team914ff442020-02-20 12:34:37 -0800502// Prints a human-readable representation of `x` to `os`.
503std::ostream& operator<<(std::ostream& os, const Status& x);
504
Abseil Team930fbec2020-09-02 08:15:12 -0700505// IsAborted()
506// IsAlreadyExists()
507// IsCancelled()
508// IsDataLoss()
509// IsDeadlineExceeded()
510// IsFailedPrecondition()
511// IsInternal()
512// IsInvalidArgument()
513// IsNotFound()
514// IsOutOfRange()
515// IsPermissionDenied()
516// IsResourceExhausted()
517// IsUnauthenticated()
518// IsUnavailable()
519// IsUnimplemented()
520// IsUnknown()
521//
522// These convenience functions return `true` if a given status matches the
523// `absl::StatusCode` error code of its associated function.
524ABSL_MUST_USE_RESULT bool IsAborted(const Status& status);
525ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status);
526ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status);
527ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status);
528ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status);
529ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status);
530ABSL_MUST_USE_RESULT bool IsInternal(const Status& status);
531ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status);
532ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status);
533ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status);
534ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status);
535ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status);
536ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status);
537ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status);
538ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status);
539ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status);
540
541// AbortedError()
542// AlreadyExistsError()
543// CancelledError()
544// DataLossError()
545// DeadlineExceededError()
546// FailedPreconditionError()
547// InternalError()
548// InvalidArgumentError()
549// NotFoundError()
550// OutOfRangeError()
551// PermissionDeniedError()
552// ResourceExhaustedError()
553// UnauthenticatedError()
554// UnavailableError()
555// UnimplementedError()
556// UnknownError()
557//
558// These convenience functions create an `absl::Status` object with an error
559// code as indicated by the associated function name, using the error message
560// passed in `message`.
561Status AbortedError(absl::string_view message);
562Status AlreadyExistsError(absl::string_view message);
563Status CancelledError(absl::string_view message);
564Status DataLossError(absl::string_view message);
565Status DeadlineExceededError(absl::string_view message);
566Status FailedPreconditionError(absl::string_view message);
567Status InternalError(absl::string_view message);
568Status InvalidArgumentError(absl::string_view message);
569Status NotFoundError(absl::string_view message);
570Status OutOfRangeError(absl::string_view message);
571Status PermissionDeniedError(absl::string_view message);
572Status ResourceExhaustedError(absl::string_view message);
573Status UnauthenticatedError(absl::string_view message);
574Status UnavailableError(absl::string_view message);
575Status UnimplementedError(absl::string_view message);
576Status UnknownError(absl::string_view message);
577
578//------------------------------------------------------------------------------
Abseil Team914ff442020-02-20 12:34:37 -0800579// Implementation details follow
Abseil Team930fbec2020-09-02 08:15:12 -0700580//------------------------------------------------------------------------------
Abseil Team914ff442020-02-20 12:34:37 -0800581
582inline Status::Status() : rep_(CodeToInlinedRep(absl::StatusCode::kOk)) {}
583
584inline Status::Status(absl::StatusCode code) : rep_(CodeToInlinedRep(code)) {}
585
586inline Status::Status(const Status& x) : rep_(x.rep_) { Ref(rep_); }
587
588inline Status& Status::operator=(const Status& x) {
589 uintptr_t old_rep = rep_;
590 if (x.rep_ != old_rep) {
591 Ref(x.rep_);
592 rep_ = x.rep_;
593 Unref(old_rep);
594 }
595 return *this;
596}
597
598inline Status::Status(Status&& x) noexcept : rep_(x.rep_) {
599 x.rep_ = MovedFromRep();
600}
601
602inline Status& Status::operator=(Status&& x) {
603 uintptr_t old_rep = rep_;
604 rep_ = x.rep_;
605 x.rep_ = MovedFromRep();
606 Unref(old_rep);
607 return *this;
608}
609
610inline void Status::Update(const Status& new_status) {
611 if (ok()) {
612 *this = new_status;
613 }
614}
615
616inline void Status::Update(Status&& new_status) {
617 if (ok()) {
618 *this = std::move(new_status);
619 }
620}
621
622inline Status::~Status() { Unref(rep_); }
623
624inline bool Status::ok() const {
625 return rep_ == CodeToInlinedRep(absl::StatusCode::kOk);
626}
627
628inline absl::string_view Status::message() const {
629 return !IsInlined(rep_)
630 ? RepToPointer(rep_)->message
631 : (IsMovedFrom(rep_) ? absl::string_view(kMovedFromString)
632 : absl::string_view());
633}
634
635inline bool operator==(const Status& lhs, const Status& rhs) {
636 return lhs.rep_ == rhs.rep_ || Status::EqualsSlow(lhs, rhs);
637}
638
639inline bool operator!=(const Status& lhs, const Status& rhs) {
640 return !(lhs == rhs);
641}
642
643inline std::string Status::ToString() const {
644 return ok() ? "OK" : ToStringSlow();
645}
646
647inline void Status::IgnoreError() const {
648 // no-op
649}
650
651inline void swap(absl::Status& a, absl::Status& b) {
652 using std::swap;
653 swap(a.rep_, b.rep_);
654}
655
656inline const status_internal::Payloads* Status::GetPayloads() const {
657 return IsInlined(rep_) ? nullptr : RepToPointer(rep_)->payloads.get();
658}
659
660inline status_internal::Payloads* Status::GetPayloads() {
661 return IsInlined(rep_) ? nullptr : RepToPointer(rep_)->payloads.get();
662}
663
664inline bool Status::IsInlined(uintptr_t rep) { return (rep & 1) == 0; }
665
666inline bool Status::IsMovedFrom(uintptr_t rep) {
667 return IsInlined(rep) && (rep & 2) != 0;
668}
669
670inline uintptr_t Status::MovedFromRep() {
671 return CodeToInlinedRep(absl::StatusCode::kInternal) | 2;
672}
673
674inline uintptr_t Status::CodeToInlinedRep(absl::StatusCode code) {
675 return static_cast<uintptr_t>(code) << 2;
676}
677
678inline absl::StatusCode Status::InlinedRepToCode(uintptr_t rep) {
679 assert(IsInlined(rep));
680 return static_cast<absl::StatusCode>(rep >> 2);
681}
682
683inline status_internal::StatusRep* Status::RepToPointer(uintptr_t rep) {
684 assert(!IsInlined(rep));
685 return reinterpret_cast<status_internal::StatusRep*>(rep - 1);
686}
687
688inline uintptr_t Status::PointerToRep(status_internal::StatusRep* rep) {
689 return reinterpret_cast<uintptr_t>(rep) + 1;
690}
691
692inline void Status::Ref(uintptr_t rep) {
693 if (!IsInlined(rep)) {
694 RepToPointer(rep)->ref.fetch_add(1, std::memory_order_relaxed);
695 }
696}
697
698inline void Status::Unref(uintptr_t rep) {
699 if (!IsInlined(rep)) {
700 UnrefNonInlined(rep);
701 }
702}
703
704inline Status OkStatus() { return Status(); }
705
Abseil Team914ff442020-02-20 12:34:37 -0800706// Creates a `Status` object with the `absl::StatusCode::kCancelled` error code
707// and an empty message. It is provided only for efficiency, given that
708// message-less kCancelled errors are common in the infrastructure.
709inline Status CancelledError() { return Status(absl::StatusCode::kCancelled); }
710
Abseil Team914ff442020-02-20 12:34:37 -0800711ABSL_NAMESPACE_END
712} // namespace absl
713
714#endif // ABSL_STATUS_STATUS_H_