You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

status.h 38 kB

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