1 // 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.
14 //
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 propagating 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 communicating
28 // errors in C++, and is used to represent error state in both in-process
29 // library calls as well as RPC calls. Some of these errors may be recoverable,
30 // but others may not. Most functions that can produce a recoverable error
31 // should be designed to return an `absl::Status` (or `absl::StatusOr`).
32 //
33 // Example:
34 //
35 // absl::Status myFunction(absl::string_view fname, ...) {
36 // ...
37 // // encounter error
38 // if (error condition) {
39 // return absl::InvalidArgumentError("bad mode");
40 // }
41 // // else, return OK
42 // return absl::OkStatus();
43 // }
44 //
45 // An `absl::Status` is designed to either return "OK" or one of a number of
46 // different error codes, corresponding to typical error conditions.
47 // In almost all cases, when using `absl::Status` you should use the canonical
48 // error codes (of type `absl::StatusCode`) enumerated in this header file.
49 // These canonical codes are understood across the codebase and will be
50 // accepted across all API and RPC boundaries.
51 #ifndef ABSL_STATUS_STATUS_H_
52 #define ABSL_STATUS_STATUS_H_
53
54 #include <cassert>
55 #include <cstdint>
56 #include <ostream>
57 #include <string>
58 #include <utility>
59
60 #include "absl/base/attributes.h"
61 #include "absl/base/config.h"
62 #include "absl/base/macros.h"
63 #include "absl/base/nullability.h"
64 #include "absl/base/optimization.h"
65 #include "absl/functional/function_ref.h"
66 #include "absl/status/internal/status_internal.h"
67 #include "absl/strings/cord.h"
68 #include "absl/strings/string_view.h"
69 #include "absl/types/optional.h"
70
71 // TODO: crbug.com/1491724 - Remove include below when other third_party
72 // libraries stop silently rely on it.
73 #include "absl/strings/str_cat.h"
74
75 namespace absl {
76 ABSL_NAMESPACE_BEGIN
77
78 // absl::StatusCode
79 //
80 // An `absl::StatusCode` is an enumerated type indicating either no error ("OK")
81 // or an error condition. In most cases, an `absl::Status` indicates a
82 // recoverable error, and the purpose of signalling an error is to indicate what
83 // action to take in response to that error. These error codes map to the proto
84 // RPC error codes indicated in https://cloud.google.com/apis/design/errors.
85 //
86 // The errors listed below are the canonical errors associated with
87 // `absl::Status` and are used throughout the codebase. As a result, these
88 // error codes are somewhat generic.
89 //
90 // In general, try to return the most specific error that applies if more than
91 // one error may pertain. For example, prefer `kOutOfRange` over
92 // `kFailedPrecondition` if both codes apply. Similarly prefer `kNotFound` or
93 // `kAlreadyExists` over `kFailedPrecondition`.
94 //
95 // Because these errors may cross RPC boundaries, these codes are tied to the
96 // `google.rpc.Code` definitions within
97 // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
98 // The string value of these RPC codes is denoted within each enum below.
99 //
100 // If your error handling code requires more context, you can attach payloads
101 // to your status. See `absl::Status::SetPayload()` and
102 // `absl::Status::GetPayload()` below.
103 enum class StatusCode : int {
104 // StatusCode::kOk
105 //
106 // kOK (gRPC code "OK") does not indicate an error; this value is returned on
107 // success. It is typical to check for this value before proceeding on any
108 // given call across an API or RPC boundary. To check this value, use the
109 // `absl::Status::ok()` member function rather than inspecting the raw code.
110 kOk = 0,
111
112 // StatusCode::kCancelled
113 //
114 // kCancelled (gRPC code "CANCELLED") indicates the operation was cancelled,
115 // typically by the caller.
116 kCancelled = 1,
117
118 // StatusCode::kUnknown
119 //
120 // kUnknown (gRPC code "UNKNOWN") indicates an unknown error occurred. In
121 // general, more specific errors should be raised, if possible. Errors raised
122 // by APIs that do not return enough error information may be converted to
123 // this error.
124 kUnknown = 2,
125
126 // StatusCode::kInvalidArgument
127 //
128 // kInvalidArgument (gRPC code "INVALID_ARGUMENT") indicates the caller
129 // specified an invalid argument, such as a malformed filename. Note that use
130 // of such errors should be narrowly limited to indicate the invalid nature of
131 // the arguments themselves. Errors with validly formed arguments that may
132 // cause errors with the state of the receiving system should be denoted with
133 // `kFailedPrecondition` instead.
134 kInvalidArgument = 3,
135
136 // StatusCode::kDeadlineExceeded
137 //
138 // kDeadlineExceeded (gRPC code "DEADLINE_EXCEEDED") indicates a deadline
139 // expired before the operation could complete. For operations that may change
140 // state within a system, this error may be returned even if the operation has
141 // completed successfully. For example, a successful response from a server
142 // could have been delayed long enough for the deadline to expire.
143 kDeadlineExceeded = 4,
144
145 // StatusCode::kNotFound
146 //
147 // kNotFound (gRPC code "NOT_FOUND") indicates some requested entity (such as
148 // a file or directory) was not found.
149 //
150 // `kNotFound` is useful if a request should be denied for an entire class of
151 // users, such as during a gradual feature rollout or undocumented allow list.
152 // If a request should be denied for specific sets of users, such as through
153 // user-based access control, use `kPermissionDenied` instead.
154 kNotFound = 5,
155
156 // StatusCode::kAlreadyExists
157 //
158 // kAlreadyExists (gRPC code "ALREADY_EXISTS") indicates that the entity a
159 // caller attempted to create (such as a file or directory) is already
160 // present.
161 kAlreadyExists = 6,
162
163 // StatusCode::kPermissionDenied
164 //
165 // kPermissionDenied (gRPC code "PERMISSION_DENIED") indicates that the caller
166 // does not have permission to execute the specified operation. Note that this
167 // error is different than an error due to an *un*authenticated user. This
168 // error code does not imply the request is valid or the requested entity
169 // exists or satisfies any other pre-conditions.
170 //
171 // `kPermissionDenied` must not be used for rejections caused by exhausting
172 // some resource. Instead, use `kResourceExhausted` for those errors.
173 // `kPermissionDenied` must not be used if the caller cannot be identified.
174 // Instead, use `kUnauthenticated` for those errors.
175 kPermissionDenied = 7,
176
177 // StatusCode::kResourceExhausted
178 //
179 // kResourceExhausted (gRPC code "RESOURCE_EXHAUSTED") indicates some resource
180 // has been exhausted, perhaps a per-user quota, or perhaps the entire file
181 // system is out of space.
182 kResourceExhausted = 8,
183
184 // StatusCode::kFailedPrecondition
185 //
186 // kFailedPrecondition (gRPC code "FAILED_PRECONDITION") indicates that the
187 // operation was rejected because the system is not in a state required for
188 // the operation's execution. For example, a directory to be deleted may be
189 // non-empty, an "rmdir" operation is applied to a non-directory, etc.
190 //
191 // Some guidelines that may help a service implementer in deciding between
192 // `kFailedPrecondition`, `kAborted`, and `kUnavailable`:
193 //
194 // (a) Use `kUnavailable` if the client can retry just the failing call.
195 // (b) Use `kAborted` if the client should retry at a higher transaction
196 // level (such as when a client-specified test-and-set fails, indicating
197 // the client should restart a read-modify-write sequence).
198 // (c) Use `kFailedPrecondition` if the client should not retry until
199 // the system state has been explicitly fixed. For example, if a "rmdir"
200 // fails because the directory is non-empty, `kFailedPrecondition`
201 // should be returned since the client should not retry unless
202 // the files are deleted from the directory.
203 kFailedPrecondition = 9,
204
205 // StatusCode::kAborted
206 //
207 // kAborted (gRPC code "ABORTED") indicates the operation was aborted,
208 // typically due to a concurrency issue such as a sequencer check failure or a
209 // failed transaction.
210 //
211 // See the guidelines above for deciding between `kFailedPrecondition`,
212 // `kAborted`, and `kUnavailable`.
213 kAborted = 10,
214
215 // StatusCode::kOutOfRange
216 //
217 // kOutOfRange (gRPC code "OUT_OF_RANGE") indicates the operation was
218 // attempted past the valid range, such as seeking or reading past an
219 // end-of-file.
220 //
221 // Unlike `kInvalidArgument`, this error indicates a problem that may
222 // be fixed if the system state changes. For example, a 32-bit file
223 // system will generate `kInvalidArgument` if asked to read at an
224 // offset that is not in the range [0,2^32-1], but it will generate
225 // `kOutOfRange` if asked to read from an offset past the current
226 // file size.
227 //
228 // There is a fair bit of overlap between `kFailedPrecondition` and
229 // `kOutOfRange`. We recommend using `kOutOfRange` (the more specific
230 // error) when it applies so that callers who are iterating through
231 // a space can easily look for an `kOutOfRange` error to detect when
232 // they are done.
233 kOutOfRange = 11,
234
235 // StatusCode::kUnimplemented
236 //
237 // kUnimplemented (gRPC code "UNIMPLEMENTED") indicates the operation is not
238 // implemented or supported in this service. In this case, the operation
239 // should not be re-attempted.
240 kUnimplemented = 12,
241
242 // StatusCode::kInternal
243 //
244 // kInternal (gRPC code "INTERNAL") indicates an internal error has occurred
245 // and some invariants expected by the underlying system have not been
246 // satisfied. This error code is reserved for serious errors.
247 kInternal = 13,
248
249 // StatusCode::kUnavailable
250 //
251 // kUnavailable (gRPC code "UNAVAILABLE") indicates the service is currently
252 // unavailable and that this is most likely a transient condition. An error
253 // such as this can be corrected by retrying with a backoff scheme. Note that
254 // it is not always safe to retry non-idempotent operations.
255 //
256 // See the guidelines above for deciding between `kFailedPrecondition`,
257 // `kAborted`, and `kUnavailable`.
258 kUnavailable = 14,
259
260 // StatusCode::kDataLoss
261 //
262 // kDataLoss (gRPC code "DATA_LOSS") indicates that unrecoverable data loss or
263 // corruption has occurred. As this error is serious, proper alerting should
264 // be attached to errors such as this.
265 kDataLoss = 15,
266
267 // StatusCode::kUnauthenticated
268 //
269 // kUnauthenticated (gRPC code "UNAUTHENTICATED") indicates that the request
270 // does not have valid authentication credentials for the operation. Correct
271 // the authentication and try again.
272 kUnauthenticated = 16,
273
274 // StatusCode::DoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_
275 //
276 // NOTE: this error code entry should not be used and you should not rely on
277 // its value, which may change.
278 //
279 // The purpose of this enumerated value is to force people who handle status
280 // codes with `switch()` statements to *not* simply enumerate all possible
281 // values, but instead provide a "default:" case. Providing such a default
282 // case ensures that code will compile when new codes are added.
283 kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20
284 };
285
286 // StatusCodeToString()
287 //
288 // Returns the name for the status code, or "" if it is an unknown value.
289 std::string StatusCodeToString(StatusCode code);
290
291 // operator<<
292 //
293 // Streams StatusCodeToString(code) to `os`.
294 std::ostream& operator<<(std::ostream& os, StatusCode code);
295
296 // absl::StatusToStringMode
297 //
298 // An `absl::StatusToStringMode` is an enumerated type indicating how
299 // `absl::Status::ToString()` should construct the output string for a non-ok
300 // status.
301 enum class StatusToStringMode : int {
302 // ToString will not contain any extra data (such as payloads). It will only
303 // contain the error code and message, if any.
304 kWithNoExtraData = 0,
305 // ToString will contain the payloads.
306 kWithPayload = 1 << 0,
307 // ToString will include all the extra data this Status has.
308 kWithEverything = ~kWithNoExtraData,
309 // Default mode used by ToString. Its exact value might change in the future.
310 kDefault = kWithPayload,
311 };
312
313 // absl::StatusToStringMode is specified as a bitmask type, which means the
314 // following operations must be provided:
315 inline constexpr StatusToStringMode operator&(StatusToStringMode lhs,
316 StatusToStringMode rhs) {
317 return static_cast<StatusToStringMode>(static_cast<int>(lhs) &
318 static_cast<int>(rhs));
319 }
320 inline constexpr StatusToStringMode operator|(StatusToStringMode lhs,
321 StatusToStringMode rhs) {
322 return static_cast<StatusToStringMode>(static_cast<int>(lhs) |
323 static_cast<int>(rhs));
324 }
325 inline constexpr StatusToStringMode operator^(StatusToStringMode lhs,
326 StatusToStringMode rhs) {
327 return static_cast<StatusToStringMode>(static_cast<int>(lhs) ^
328 static_cast<int>(rhs));
329 }
330 inline constexpr StatusToStringMode operator~(StatusToStringMode arg) {
331 return static_cast<StatusToStringMode>(~static_cast<int>(arg));
332 }
333 inline StatusToStringMode& operator&=(StatusToStringMode& lhs,
334 StatusToStringMode rhs) {
335 lhs = lhs & rhs;
336 return lhs;
337 }
338 inline StatusToStringMode& operator|=(StatusToStringMode& lhs,
339 StatusToStringMode rhs) {
340 lhs = lhs | rhs;
341 return lhs;
342 }
343 inline StatusToStringMode& operator^=(StatusToStringMode& lhs,
344 StatusToStringMode rhs) {
345 lhs = lhs ^ rhs;
346 return lhs;
347 }
348
349 // absl::Status
350 //
351 // The `absl::Status` class is generally used to gracefully handle errors
352 // across API boundaries (and in particular across RPC boundaries). Some of
353 // these errors may be recoverable, but others may not. Most
354 // functions which can produce a recoverable error should be designed to return
355 // either an `absl::Status` (or the similar `absl::StatusOr<T>`, which holds
356 // either an object of type `T` or an error).
357 //
358 // API developers should construct their functions to return `absl::OkStatus()`
359 // upon success, or an `absl::StatusCode` upon another type of error (e.g
360 // an `absl::StatusCode::kInvalidArgument` error). The API provides convenience
361 // functions to construct each status code.
362 //
363 // Example:
364 //
365 // absl::Status myFunction(absl::string_view fname, ...) {
366 // ...
367 // // encounter error
368 // if (error condition) {
369 // // Construct an absl::StatusCode::kInvalidArgument error
370 // return absl::InvalidArgumentError("bad mode");
371 // }
372 // // else, return OK
373 // return absl::OkStatus();
374 // }
375 //
376 // Users handling status error codes should prefer checking for an OK status
377 // using the `ok()` member function. Handling multiple error codes may justify
378 // use of switch statement, but only check for error codes you know how to
379 // handle; do not try to exhaustively match against all canonical error codes.
380 // Errors that cannot be handled should be logged and/or propagated for higher
381 // levels to deal with. If you do use a switch statement, make sure that you
382 // also provide a `default:` switch case, so that code does not break as other
383 // canonical codes are added to the API.
384 //
385 // Example:
386 //
387 // absl::Status result = DoSomething();
388 // if (!result.ok()) {
389 // LOG(ERROR) << result;
390 // }
391 //
392 // // Provide a default if switching on multiple error codes
393 // switch (result.code()) {
394 // // The user hasn't authenticated. Ask them to reauth
395 // case absl::StatusCode::kUnauthenticated:
396 // DoReAuth();
397 // break;
398 // // The user does not have permission. Log an error.
399 // case absl::StatusCode::kPermissionDenied:
400 // LOG(ERROR) << result;
401 // break;
402 // // Propagate the error otherwise.
403 // default:
404 // return true;
405 // }
406 //
407 // An `absl::Status` can optionally include a payload with more information
408 // about the error. Typically, this payload serves one of several purposes:
409 //
410 // * It may provide more fine-grained semantic information about the error to
411 // facilitate actionable remedies.
412 // * It may provide human-readable contextual information that is more
413 // appropriate to display to an end user.
414 //
415 // Example:
416 //
417 // absl::Status result = DoSomething();
418 // // Inform user to retry after 30 seconds
419 // // See more error details in googleapis/google/rpc/error_details.proto
420 // if (absl::IsResourceExhausted(result)) {
421 // google::rpc::RetryInfo info;
422 // info.retry_delay().seconds() = 30;
423 // // Payloads require a unique key (a URL to ensure no collisions with
424 // // other payloads), and an `absl::Cord` to hold the encoded data.
425 // absl::string_view url = "type.googleapis.com/google.rpc.RetryInfo";
426 // result.SetPayload(url, info.SerializeAsCord());
427 // return result;
428 // }
429 //
430 // For documentation see https://abseil.io/docs/cpp/guides/status.
431 //
432 // Returned Status objects may not be ignored. status_internal.h has a forward
433 // declaration of the form
434 // class ABSL_MUST_USE_RESULT Status;
435 class ABSL_ATTRIBUTE_TRIVIAL_ABI Status final {
436 public:
437 // Constructors
438
439 // This default constructor creates an OK status with no message or payload.
440 // Avoid this constructor and prefer explicit construction of an OK status
441 // with `absl::OkStatus()`.
442 Status();
443
444 // Creates a status in the canonical error space with the specified
445 // `absl::StatusCode` and error message. If `code == absl::StatusCode::kOk`, // NOLINT
446 // `msg` is ignored and an object identical to an OK status is constructed.
447 //
448 // The `msg` string must be in UTF-8. The implementation may complain (e.g., // NOLINT
449 // by printing a warning) if it is not.
450 Status(absl::StatusCode code, absl::string_view msg);
451
452 Status(const Status&);
453 Status& operator=(const Status& x);
454
455 // Move operators
456
457 // The moved-from state is valid but unspecified.
458 Status(Status&&) noexcept;
459 Status& operator=(Status&&) noexcept;
460
461 ~Status();
462
463 // Status::Update()
464 //
465 // Updates the existing status with `new_status` provided that `this->ok()`.
466 // If the existing status already contains a non-OK error, this update has no
467 // effect and preserves the current data. Note that this behavior may change
468 // in the future to augment a current non-ok status with additional
469 // information about `new_status`.
470 //
471 // `Update()` provides a convenient way of keeping track of the first error
472 // encountered.
473 //
474 // Example:
475 // // Instead of "if (overall_status.ok()) overall_status = new_status"
476 // overall_status.Update(new_status);
477 //
478 void Update(const Status& new_status);
479 void Update(Status&& new_status);
480
481 // Status::ok()
482 //
483 // Returns `true` if `this->code()` == `absl::StatusCode::kOk`,
484 // indicating the absence of an error.
485 // Prefer checking for an OK status using this member function.
486 ABSL_MUST_USE_RESULT bool ok() const;
487
488 // Status::code()
489 //
490 // Returns the canonical error code of type `absl::StatusCode` of this status.
491 absl::StatusCode code() const;
492
493 // Status::raw_code()
494 //
495 // Returns a raw (canonical) error code corresponding to the enum value of
496 // `google.rpc.Code` definitions within
497 // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto.
498 // These values could be out of the range of canonical `absl::StatusCode`
499 // enum values.
500 //
501 // NOTE: This function should only be called when converting to an associated
502 // wire format. Use `Status::code()` for error handling.
503 int raw_code() const;
504
505 // Status::message()
506 //
507 // Returns the error message associated with this error code, if available.
508 // Note that this message rarely describes the error code. It is not unusual
509 // for the error message to be the empty string. As a result, prefer
510 // `operator<<` or `Status::ToString()` for debug logging.
511 absl::string_view message() const;
512
513 friend bool operator==(const Status&, const Status&);
514 friend bool operator!=(const Status&, const Status&);
515
516 // Status::ToString()
517 //
518 // Returns a string based on the `mode`. By default, it returns combination of
519 // the error code name, the message and any associated payload messages. This
520 // string is designed simply to be human readable and its exact format should
521 // not be load bearing. Do not depend on the exact format of the result of
522 // `ToString()` which is subject to change.
523 //
524 // The printed code name and the message are generally substrings of the
525 // result, and the payloads to be printed use the status payload printer
526 // mechanism (which is internal).
527 std::string ToString(
528 StatusToStringMode mode = StatusToStringMode::kDefault) const;
529
530 // Support `absl::StrCat`, `absl::StrFormat`, etc.
531 template <typename Sink>
AbslStringify(Sink & sink,const Status & status)532 friend void AbslStringify(Sink& sink, const Status& status) {
533 sink.Append(status.ToString(StatusToStringMode::kWithEverything));
534 }
535
536 // Status::IgnoreError()
537 //
538 // Ignores any errors. This method does nothing except potentially suppress
539 // complaints from any tools that are checking that errors are not dropped on
540 // the floor.
541 void IgnoreError() const;
542
543 // swap()
544 //
545 // Swap the contents of one status with another.
546 friend void swap(Status& a, Status& b) noexcept;
547
548 //----------------------------------------------------------------------------
549 // Payload Management APIs
550 //----------------------------------------------------------------------------
551
552 // A payload may be attached to a status to provide additional context to an
553 // error that may not be satisfied by an existing `absl::StatusCode`.
554 // Typically, this payload serves one of several purposes:
555 //
556 // * It may provide more fine-grained semantic information about the error
557 // to facilitate actionable remedies.
558 // * It may provide human-readable contextual information that is more
559 // appropriate to display to an end user.
560 //
561 // A payload consists of a [key,value] pair, where the key is a string
562 // referring to a unique "type URL" and the value is an object of type
563 // `absl::Cord` to hold the contextual data.
564 //
565 // The "type URL" should be unique and follow the format of a URL
566 // (https://en.wikipedia.org/wiki/URL) and, ideally, provide some
567 // documentation or schema on how to interpret its associated data. For
568 // example, the default type URL for a protobuf message type is
569 // "type.googleapis.com/packagename.messagename". Other custom wire formats
570 // should define the format of type URL in a similar practice so as to
571 // minimize the chance of conflict between type URLs.
572 // Users should ensure that the type URL can be mapped to a concrete
573 // C++ type if they want to deserialize the payload and read it effectively.
574 //
575 // To attach a payload to a status object, call `Status::SetPayload()`,
576 // passing it the type URL and an `absl::Cord` of associated data. Similarly,
577 // to extract the payload from a status, call `Status::GetPayload()`. You
578 // may attach multiple payloads (with differing type URLs) to any given
579 // status object, provided that the status is currently exhibiting an error
580 // code (i.e. is not OK).
581
582 // Status::GetPayload()
583 //
584 // Gets the payload of a status given its unique `type_url` key, if present.
585 absl::optional<absl::Cord> GetPayload(absl::string_view type_url) const;
586
587 // Status::SetPayload()
588 //
589 // Sets the payload for a non-ok status using a `type_url` key, overwriting
590 // any existing payload for that `type_url`.
591 //
592 // NOTE: This function does nothing if the Status is ok.
593 void SetPayload(absl::string_view type_url, absl::Cord payload);
594
595 // Status::ErasePayload()
596 //
597 // Erases the payload corresponding to the `type_url` key. Returns `true` if
598 // the payload was present.
599 bool ErasePayload(absl::string_view type_url);
600
601 // Status::ForEachPayload()
602 //
603 // Iterates over the stored payloads and calls the
604 // `visitor(type_key, payload)` callable for each one.
605 //
606 // NOTE: The order of calls to `visitor()` is not specified and may change at
607 // any time.
608 //
609 // NOTE: Any mutation on the same 'absl::Status' object during visitation is
610 // forbidden and could result in undefined behavior.
611 void ForEachPayload(
612 absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
613 const;
614
615 private:
616 friend Status CancelledError();
617
618 // Creates a status in the canonical error space with the specified
619 // code, and an empty error message.
620 explicit Status(absl::StatusCode code);
621
622 // Underlying constructor for status from a rep_.
Status(uintptr_t rep)623 explicit Status(uintptr_t rep) : rep_(rep) {}
624
625 static void Ref(uintptr_t rep);
626 static void Unref(uintptr_t rep);
627
628 // REQUIRES: !ok()
629 // Ensures rep is not inlined or shared with any other Status.
630 static absl::Nonnull<status_internal::StatusRep*> PrepareToModify(
631 uintptr_t rep);
632
633 // MSVC 14.0 limitation requires the const.
634 static constexpr const char kMovedFromString[] =
635 "Status accessed after move.";
636
637 static absl::Nonnull<const std::string*> EmptyString();
638 static absl::Nonnull<const std::string*> MovedFromString();
639
640 // Returns whether rep contains an inlined representation.
641 // See rep_ for details.
642 static constexpr bool IsInlined(uintptr_t rep);
643
644 // Indicates whether this Status was the rhs of a move operation. See rep_
645 // for details.
646 static constexpr bool IsMovedFrom(uintptr_t rep);
647 static constexpr uintptr_t MovedFromRep();
648
649 // Convert between error::Code and the inlined uintptr_t representation used
650 // by rep_. See rep_ for details.
651 static constexpr uintptr_t CodeToInlinedRep(absl::StatusCode code);
652 static constexpr absl::StatusCode InlinedRepToCode(uintptr_t rep);
653
654 // Converts between StatusRep* and the external uintptr_t representation used
655 // by rep_. See rep_ for details.
656 static uintptr_t PointerToRep(status_internal::StatusRep* r);
657 static absl::Nonnull<const status_internal::StatusRep*> RepToPointer(
658 uintptr_t r);
659
660 static std::string ToStringSlow(uintptr_t rep, StatusToStringMode mode);
661
662 // Status supports two different representations.
663 // - When the low bit is set it is an inlined representation.
664 // It uses the canonical error space, no message or payload.
665 // The error code is (rep_ >> 2).
666 // The (rep_ & 2) bit is the "moved from" indicator, used in IsMovedFrom().
667 // - When the low bit is off it is an external representation.
668 // In this case all the data comes from a heap allocated Rep object.
669 // rep_ is a status_internal::StatusRep* pointer to that structure.
670 uintptr_t rep_;
671
672 friend class status_internal::StatusRep;
673 };
674
675 // OkStatus()
676 //
677 // Returns an OK status, equivalent to a default constructed instance. Prefer
678 // usage of `absl::OkStatus()` when constructing such an OK status.
679 Status OkStatus();
680
681 // operator<<()
682 //
683 // Prints a human-readable representation of `x` to `os`.
684 std::ostream& operator<<(std::ostream& os, const Status& x);
685
686 // IsAborted()
687 // IsAlreadyExists()
688 // IsCancelled()
689 // IsDataLoss()
690 // IsDeadlineExceeded()
691 // IsFailedPrecondition()
692 // IsInternal()
693 // IsInvalidArgument()
694 // IsNotFound()
695 // IsOutOfRange()
696 // IsPermissionDenied()
697 // IsResourceExhausted()
698 // IsUnauthenticated()
699 // IsUnavailable()
700 // IsUnimplemented()
701 // IsUnknown()
702 //
703 // These convenience functions return `true` if a given status matches the
704 // `absl::StatusCode` error code of its associated function.
705 ABSL_MUST_USE_RESULT bool IsAborted(const Status& status);
706 ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status);
707 ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status);
708 ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status);
709 ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status);
710 ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status);
711 ABSL_MUST_USE_RESULT bool IsInternal(const Status& status);
712 ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status);
713 ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status);
714 ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status);
715 ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status);
716 ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status);
717 ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status);
718 ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status);
719 ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status);
720 ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status);
721
722 // AbortedError()
723 // AlreadyExistsError()
724 // CancelledError()
725 // DataLossError()
726 // DeadlineExceededError()
727 // FailedPreconditionError()
728 // InternalError()
729 // InvalidArgumentError()
730 // NotFoundError()
731 // OutOfRangeError()
732 // PermissionDeniedError()
733 // ResourceExhaustedError()
734 // UnauthenticatedError()
735 // UnavailableError()
736 // UnimplementedError()
737 // UnknownError()
738 //
739 // These convenience functions create an `absl::Status` object with an error
740 // code as indicated by the associated function name, using the error message
741 // passed in `message`.
742 Status AbortedError(absl::string_view message);
743 Status AlreadyExistsError(absl::string_view message);
744 Status CancelledError(absl::string_view message);
745 Status DataLossError(absl::string_view message);
746 Status DeadlineExceededError(absl::string_view message);
747 Status FailedPreconditionError(absl::string_view message);
748 Status InternalError(absl::string_view message);
749 Status InvalidArgumentError(absl::string_view message);
750 Status NotFoundError(absl::string_view message);
751 Status OutOfRangeError(absl::string_view message);
752 Status PermissionDeniedError(absl::string_view message);
753 Status ResourceExhaustedError(absl::string_view message);
754 Status UnauthenticatedError(absl::string_view message);
755 Status UnavailableError(absl::string_view message);
756 Status UnimplementedError(absl::string_view message);
757 Status UnknownError(absl::string_view message);
758
759 // ErrnoToStatusCode()
760 //
761 // Returns the StatusCode for `error_number`, which should be an `errno` value.
762 // See https://en.cppreference.com/w/cpp/error/errno_macros and similar
763 // references.
764 absl::StatusCode ErrnoToStatusCode(int error_number);
765
766 // ErrnoToStatus()
767 //
768 // Convenience function that creates a `absl::Status` using an `error_number`,
769 // which should be an `errno` value.
770 Status ErrnoToStatus(int error_number, absl::string_view message);
771
772 //------------------------------------------------------------------------------
773 // Implementation details follow
774 //------------------------------------------------------------------------------
775
Status()776 inline Status::Status() : Status(absl::StatusCode::kOk) {}
777
Status(absl::StatusCode code)778 inline Status::Status(absl::StatusCode code) : Status(CodeToInlinedRep(code)) {}
779
Status(const Status & x)780 inline Status::Status(const Status& x) : Status(x.rep_) { Ref(rep_); }
781
782 inline Status& Status::operator=(const Status& x) {
783 uintptr_t old_rep = rep_;
784 if (x.rep_ != old_rep) {
785 Ref(x.rep_);
786 rep_ = x.rep_;
787 Unref(old_rep);
788 }
789 return *this;
790 }
791
Status(Status && x)792 inline Status::Status(Status&& x) noexcept : Status(x.rep_) {
793 x.rep_ = MovedFromRep();
794 }
795
796 inline Status& Status::operator=(Status&& x) noexcept {
797 uintptr_t old_rep = rep_;
798 if (x.rep_ != old_rep) {
799 rep_ = x.rep_;
800 x.rep_ = MovedFromRep();
801 Unref(old_rep);
802 }
803 return *this;
804 }
805
Update(const Status & new_status)806 inline void Status::Update(const Status& new_status) {
807 if (ok()) {
808 *this = new_status;
809 }
810 }
811
Update(Status && new_status)812 inline void Status::Update(Status&& new_status) {
813 if (ok()) {
814 *this = std::move(new_status);
815 }
816 }
817
~Status()818 inline Status::~Status() { Unref(rep_); }
819
ok()820 inline bool Status::ok() const {
821 return rep_ == CodeToInlinedRep(absl::StatusCode::kOk);
822 }
823
code()824 inline absl::StatusCode Status::code() const {
825 return status_internal::MapToLocalCode(raw_code());
826 }
827
raw_code()828 inline int Status::raw_code() const {
829 if (IsInlined(rep_)) return static_cast<int>(InlinedRepToCode(rep_));
830 return static_cast<int>(RepToPointer(rep_)->code());
831 }
832
message()833 inline absl::string_view Status::message() const {
834 return !IsInlined(rep_)
835 ? RepToPointer(rep_)->message()
836 : (IsMovedFrom(rep_) ? absl::string_view(kMovedFromString)
837 : absl::string_view());
838 }
839
840 inline bool operator==(const Status& lhs, const Status& rhs) {
841 if (lhs.rep_ == rhs.rep_) return true;
842 if (Status::IsInlined(lhs.rep_)) return false;
843 if (Status::IsInlined(rhs.rep_)) return false;
844 return *Status::RepToPointer(lhs.rep_) == *Status::RepToPointer(rhs.rep_);
845 }
846
847 inline bool operator!=(const Status& lhs, const Status& rhs) {
848 return !(lhs == rhs);
849 }
850
ToString(StatusToStringMode mode)851 inline std::string Status::ToString(StatusToStringMode mode) const {
852 return ok() ? "OK" : ToStringSlow(rep_, mode);
853 }
854
IgnoreError()855 inline void Status::IgnoreError() const {
856 // no-op
857 }
858
swap(absl::Status & a,absl::Status & b)859 inline void swap(absl::Status& a, absl::Status& b) noexcept {
860 using std::swap;
861 swap(a.rep_, b.rep_);
862 }
863
GetPayload(absl::string_view type_url)864 inline absl::optional<absl::Cord> Status::GetPayload(
865 absl::string_view type_url) const {
866 if (IsInlined(rep_)) return absl::nullopt;
867 return RepToPointer(rep_)->GetPayload(type_url);
868 }
869
SetPayload(absl::string_view type_url,absl::Cord payload)870 inline void Status::SetPayload(absl::string_view type_url, absl::Cord payload) {
871 if (ok()) return;
872 status_internal::StatusRep* rep = PrepareToModify(rep_);
873 rep->SetPayload(type_url, std::move(payload));
874 rep_ = PointerToRep(rep);
875 }
876
ErasePayload(absl::string_view type_url)877 inline bool Status::ErasePayload(absl::string_view type_url) {
878 if (IsInlined(rep_)) return false;
879 status_internal::StatusRep* rep = PrepareToModify(rep_);
880 auto res = rep->ErasePayload(type_url);
881 rep_ = res.new_rep;
882 return res.erased;
883 }
884
ForEachPayload(absl::FunctionRef<void (absl::string_view,const absl::Cord &)> visitor)885 inline void Status::ForEachPayload(
886 absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
887 const {
888 if (IsInlined(rep_)) return;
889 RepToPointer(rep_)->ForEachPayload(visitor);
890 }
891
IsInlined(uintptr_t rep)892 constexpr bool Status::IsInlined(uintptr_t rep) { return (rep & 1) != 0; }
893
IsMovedFrom(uintptr_t rep)894 constexpr bool Status::IsMovedFrom(uintptr_t rep) { return (rep & 2) != 0; }
895
CodeToInlinedRep(absl::StatusCode code)896 constexpr uintptr_t Status::CodeToInlinedRep(absl::StatusCode code) {
897 return (static_cast<uintptr_t>(code) << 2) + 1;
898 }
899
InlinedRepToCode(uintptr_t rep)900 constexpr absl::StatusCode Status::InlinedRepToCode(uintptr_t rep) {
901 ABSL_ASSERT(IsInlined(rep));
902 return static_cast<absl::StatusCode>(rep >> 2);
903 }
904
MovedFromRep()905 constexpr uintptr_t Status::MovedFromRep() {
906 return CodeToInlinedRep(absl::StatusCode::kInternal) | 2;
907 }
908
RepToPointer(uintptr_t rep)909 inline absl::Nonnull<const status_internal::StatusRep*> Status::RepToPointer(
910 uintptr_t rep) {
911 assert(!IsInlined(rep));
912 return reinterpret_cast<const status_internal::StatusRep*>(rep);
913 }
914
PointerToRep(absl::Nonnull<status_internal::StatusRep * > rep)915 inline uintptr_t Status::PointerToRep(
916 absl::Nonnull<status_internal::StatusRep*> rep) {
917 return reinterpret_cast<uintptr_t>(rep);
918 }
919
Ref(uintptr_t rep)920 inline void Status::Ref(uintptr_t rep) {
921 if (!IsInlined(rep)) RepToPointer(rep)->Ref();
922 }
923
Unref(uintptr_t rep)924 inline void Status::Unref(uintptr_t rep) {
925 if (!IsInlined(rep)) RepToPointer(rep)->Unref();
926 }
927
OkStatus()928 inline Status OkStatus() { return Status(); }
929
930 // Creates a `Status` object with the `absl::StatusCode::kCancelled` error code
931 // and an empty message. It is provided only for efficiency, given that
932 // message-less kCancelled errors are common in the infrastructure.
CancelledError()933 inline Status CancelledError() { return Status(absl::StatusCode::kCancelled); }
934
935 // Retrieves a message's status as a null terminated C string. The lifetime of
936 // this string is tied to the lifetime of the status object itself.
937 //
938 // If the status's message is empty, the empty string is returned.
939 //
940 // StatusMessageAsCStr exists for C support. Use `status.message()` in C++.
941 absl::Nonnull<const char*> StatusMessageAsCStr(
942 const Status& status ABSL_ATTRIBUTE_LIFETIME_BOUND);
943
944 ABSL_NAMESPACE_END
945 } // namespace absl
946
947 #endif // ABSL_STATUS_STATUS_H_
948