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