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