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