status.h 31 KB

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