![]() |
|
|||
File indexing completed on 2025-02-28 09:32:18
0001 // Copyright 2019 The Abseil Authors. 0002 // 0003 // Licensed under the Apache License, Version 2.0 (the "License"); 0004 // you may not use this file except in compliance with the License. 0005 // You may obtain a copy of the License at 0006 // 0007 // https://www.apache.org/licenses/LICENSE-2.0 0008 // 0009 // Unless required by applicable law or agreed to in writing, software 0010 // distributed under the License is distributed on an "AS IS" BASIS, 0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 0012 // See the License for the specific language governing permissions and 0013 // limitations under the License. 0014 // 0015 // ----------------------------------------------------------------------------- 0016 // File: status.h 0017 // ----------------------------------------------------------------------------- 0018 // 0019 // This header file defines the Abseil `status` library, consisting of: 0020 // 0021 // * An `absl::Status` class for holding error handling information 0022 // * A set of canonical `absl::StatusCode` error codes, and associated 0023 // utilities for generating and propagating status codes. 0024 // * A set of helper functions for creating status codes and checking their 0025 // values 0026 // 0027 // Within Google, `absl::Status` is the primary mechanism for communicating 0028 // errors in C++, and is used to represent error state in both in-process 0029 // library calls as well as RPC calls. Some of these errors may be recoverable, 0030 // but others may not. Most functions that can produce a recoverable error 0031 // should be designed to return an `absl::Status` (or `absl::StatusOr`). 0032 // 0033 // Example: 0034 // 0035 // absl::Status myFunction(absl::string_view fname, ...) { 0036 // ... 0037 // // encounter error 0038 // if (error condition) { 0039 // return absl::InvalidArgumentError("bad mode"); 0040 // } 0041 // // else, return OK 0042 // return absl::OkStatus(); 0043 // } 0044 // 0045 // An `absl::Status` is designed to either return "OK" or one of a number of 0046 // different error codes, corresponding to typical error conditions. 0047 // In almost all cases, when using `absl::Status` you should use the canonical 0048 // error codes (of type `absl::StatusCode`) enumerated in this header file. 0049 // These canonical codes are understood across the codebase and will be 0050 // accepted across all API and RPC boundaries. 0051 #ifndef ABSL_STATUS_STATUS_H_ 0052 #define ABSL_STATUS_STATUS_H_ 0053 0054 #include <cassert> 0055 #include <cstdint> 0056 #include <ostream> 0057 #include <string> 0058 #include <utility> 0059 0060 #include "absl/base/attributes.h" 0061 #include "absl/base/config.h" 0062 #include "absl/base/macros.h" 0063 #include "absl/base/nullability.h" 0064 #include "absl/base/optimization.h" 0065 #include "absl/functional/function_ref.h" 0066 #include "absl/status/internal/status_internal.h" 0067 #include "absl/strings/cord.h" 0068 #include "absl/strings/string_view.h" 0069 #include "absl/types/optional.h" 0070 0071 namespace absl { 0072 ABSL_NAMESPACE_BEGIN 0073 0074 // absl::StatusCode 0075 // 0076 // An `absl::StatusCode` is an enumerated type indicating either no error ("OK") 0077 // or an error condition. In most cases, an `absl::Status` indicates a 0078 // recoverable error, and the purpose of signalling an error is to indicate what 0079 // action to take in response to that error. These error codes map to the proto 0080 // RPC error codes indicated in https://cloud.google.com/apis/design/errors. 0081 // 0082 // The errors listed below are the canonical errors associated with 0083 // `absl::Status` and are used throughout the codebase. As a result, these 0084 // error codes are somewhat generic. 0085 // 0086 // In general, try to return the most specific error that applies if more than 0087 // one error may pertain. For example, prefer `kOutOfRange` over 0088 // `kFailedPrecondition` if both codes apply. Similarly prefer `kNotFound` or 0089 // `kAlreadyExists` over `kFailedPrecondition`. 0090 // 0091 // Because these errors may cross RPC boundaries, these codes are tied to the 0092 // `google.rpc.Code` definitions within 0093 // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto 0094 // The string value of these RPC codes is denoted within each enum below. 0095 // 0096 // If your error handling code requires more context, you can attach payloads 0097 // to your status. See `absl::Status::SetPayload()` and 0098 // `absl::Status::GetPayload()` below. 0099 enum class StatusCode : int { 0100 // StatusCode::kOk 0101 // 0102 // kOK (gRPC code "OK") does not indicate an error; this value is returned on 0103 // success. It is typical to check for this value before proceeding on any 0104 // given call across an API or RPC boundary. To check this value, use the 0105 // `absl::Status::ok()` member function rather than inspecting the raw code. 0106 kOk = 0, 0107 0108 // StatusCode::kCancelled 0109 // 0110 // kCancelled (gRPC code "CANCELLED") indicates the operation was cancelled, 0111 // typically by the caller. 0112 kCancelled = 1, 0113 0114 // StatusCode::kUnknown 0115 // 0116 // kUnknown (gRPC code "UNKNOWN") indicates an unknown error occurred. In 0117 // general, more specific errors should be raised, if possible. Errors raised 0118 // by APIs that do not return enough error information may be converted to 0119 // this error. 0120 kUnknown = 2, 0121 0122 // StatusCode::kInvalidArgument 0123 // 0124 // kInvalidArgument (gRPC code "INVALID_ARGUMENT") indicates the caller 0125 // specified an invalid argument, such as a malformed filename. Note that use 0126 // of such errors should be narrowly limited to indicate the invalid nature of 0127 // the arguments themselves. Errors with validly formed arguments that may 0128 // cause errors with the state of the receiving system should be denoted with 0129 // `kFailedPrecondition` instead. 0130 kInvalidArgument = 3, 0131 0132 // StatusCode::kDeadlineExceeded 0133 // 0134 // kDeadlineExceeded (gRPC code "DEADLINE_EXCEEDED") indicates a deadline 0135 // expired before the operation could complete. For operations that may change 0136 // state within a system, this error may be returned even if the operation has 0137 // completed successfully. For example, a successful response from a server 0138 // could have been delayed long enough for the deadline to expire. 0139 kDeadlineExceeded = 4, 0140 0141 // StatusCode::kNotFound 0142 // 0143 // kNotFound (gRPC code "NOT_FOUND") indicates some requested entity (such as 0144 // a file or directory) was not found. 0145 // 0146 // `kNotFound` is useful if a request should be denied for an entire class of 0147 // users, such as during a gradual feature rollout or undocumented allow list. 0148 // If a request should be denied for specific sets of users, such as through 0149 // user-based access control, use `kPermissionDenied` instead. 0150 kNotFound = 5, 0151 0152 // StatusCode::kAlreadyExists 0153 // 0154 // kAlreadyExists (gRPC code "ALREADY_EXISTS") indicates that the entity a 0155 // caller attempted to create (such as a file or directory) is already 0156 // present. 0157 kAlreadyExists = 6, 0158 0159 // StatusCode::kPermissionDenied 0160 // 0161 // kPermissionDenied (gRPC code "PERMISSION_DENIED") indicates that the caller 0162 // does not have permission to execute the specified operation. Note that this 0163 // error is different than an error due to an *un*authenticated user. This 0164 // error code does not imply the request is valid or the requested entity 0165 // exists or satisfies any other pre-conditions. 0166 // 0167 // `kPermissionDenied` must not be used for rejections caused by exhausting 0168 // some resource. Instead, use `kResourceExhausted` for those errors. 0169 // `kPermissionDenied` must not be used if the caller cannot be identified. 0170 // Instead, use `kUnauthenticated` for those errors. 0171 kPermissionDenied = 7, 0172 0173 // StatusCode::kResourceExhausted 0174 // 0175 // kResourceExhausted (gRPC code "RESOURCE_EXHAUSTED") indicates some resource 0176 // has been exhausted, perhaps a per-user quota, or perhaps the entire file 0177 // system is out of space. 0178 kResourceExhausted = 8, 0179 0180 // StatusCode::kFailedPrecondition 0181 // 0182 // kFailedPrecondition (gRPC code "FAILED_PRECONDITION") indicates that the 0183 // operation was rejected because the system is not in a state required for 0184 // the operation's execution. For example, a directory to be deleted may be 0185 // non-empty, an "rmdir" operation is applied to a non-directory, etc. 0186 // 0187 // Some guidelines that may help a service implementer in deciding between 0188 // `kFailedPrecondition`, `kAborted`, and `kUnavailable`: 0189 // 0190 // (a) Use `kUnavailable` if the client can retry just the failing call. 0191 // (b) Use `kAborted` if the client should retry at a higher transaction 0192 // level (such as when a client-specified test-and-set fails, indicating 0193 // the client should restart a read-modify-write sequence). 0194 // (c) Use `kFailedPrecondition` if the client should not retry until 0195 // the system state has been explicitly fixed. For example, if a "rmdir" 0196 // fails because the directory is non-empty, `kFailedPrecondition` 0197 // should be returned since the client should not retry unless 0198 // the files are deleted from the directory. 0199 kFailedPrecondition = 9, 0200 0201 // StatusCode::kAborted 0202 // 0203 // kAborted (gRPC code "ABORTED") indicates the operation was aborted, 0204 // typically due to a concurrency issue such as a sequencer check failure or a 0205 // failed transaction. 0206 // 0207 // See the guidelines above for deciding between `kFailedPrecondition`, 0208 // `kAborted`, and `kUnavailable`. 0209 kAborted = 10, 0210 0211 // StatusCode::kOutOfRange 0212 // 0213 // kOutOfRange (gRPC code "OUT_OF_RANGE") indicates the operation was 0214 // attempted past the valid range, such as seeking or reading past an 0215 // end-of-file. 0216 // 0217 // Unlike `kInvalidArgument`, this error indicates a problem that may 0218 // be fixed if the system state changes. For example, a 32-bit file 0219 // system will generate `kInvalidArgument` if asked to read at an 0220 // offset that is not in the range [0,2^32-1], but it will generate 0221 // `kOutOfRange` if asked to read from an offset past the current 0222 // file size. 0223 // 0224 // There is a fair bit of overlap between `kFailedPrecondition` and 0225 // `kOutOfRange`. We recommend using `kOutOfRange` (the more specific 0226 // error) when it applies so that callers who are iterating through 0227 // a space can easily look for an `kOutOfRange` error to detect when 0228 // they are done. 0229 kOutOfRange = 11, 0230 0231 // StatusCode::kUnimplemented 0232 // 0233 // kUnimplemented (gRPC code "UNIMPLEMENTED") indicates the operation is not 0234 // implemented or supported in this service. In this case, the operation 0235 // should not be re-attempted. 0236 kUnimplemented = 12, 0237 0238 // StatusCode::kInternal 0239 // 0240 // kInternal (gRPC code "INTERNAL") indicates an internal error has occurred 0241 // and some invariants expected by the underlying system have not been 0242 // satisfied. This error code is reserved for serious errors. 0243 kInternal = 13, 0244 0245 // StatusCode::kUnavailable 0246 // 0247 // kUnavailable (gRPC code "UNAVAILABLE") indicates the service is currently 0248 // unavailable and that this is most likely a transient condition. An error 0249 // such as this can be corrected by retrying with a backoff scheme. Note that 0250 // it is not always safe to retry non-idempotent operations. 0251 // 0252 // See the guidelines above for deciding between `kFailedPrecondition`, 0253 // `kAborted`, and `kUnavailable`. 0254 kUnavailable = 14, 0255 0256 // StatusCode::kDataLoss 0257 // 0258 // kDataLoss (gRPC code "DATA_LOSS") indicates that unrecoverable data loss or 0259 // corruption has occurred. As this error is serious, proper alerting should 0260 // be attached to errors such as this. 0261 kDataLoss = 15, 0262 0263 // StatusCode::kUnauthenticated 0264 // 0265 // kUnauthenticated (gRPC code "UNAUTHENTICATED") indicates that the request 0266 // does not have valid authentication credentials for the operation. Correct 0267 // the authentication and try again. 0268 kUnauthenticated = 16, 0269 0270 // StatusCode::DoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ 0271 // 0272 // NOTE: this error code entry should not be used and you should not rely on 0273 // its value, which may change. 0274 // 0275 // The purpose of this enumerated value is to force people who handle status 0276 // codes with `switch()` statements to *not* simply enumerate all possible 0277 // values, but instead provide a "default:" case. Providing such a default 0278 // case ensures that code will compile when new codes are added. 0279 kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20 0280 }; 0281 0282 // StatusCodeToString() 0283 // 0284 // Returns the name for the status code, or "" if it is an unknown value. 0285 std::string StatusCodeToString(StatusCode code); 0286 0287 // operator<< 0288 // 0289 // Streams StatusCodeToString(code) to `os`. 0290 std::ostream& operator<<(std::ostream& os, StatusCode code); 0291 0292 // absl::StatusToStringMode 0293 // 0294 // An `absl::StatusToStringMode` is an enumerated type indicating how 0295 // `absl::Status::ToString()` should construct the output string for a non-ok 0296 // status. 0297 enum class StatusToStringMode : int { 0298 // ToString will not contain any extra data (such as payloads). It will only 0299 // contain the error code and message, if any. 0300 kWithNoExtraData = 0, 0301 // ToString will contain the payloads. 0302 kWithPayload = 1 << 0, 0303 // ToString will include all the extra data this Status has. 0304 kWithEverything = ~kWithNoExtraData, 0305 // Default mode used by ToString. Its exact value might change in the future. 0306 kDefault = kWithPayload, 0307 }; 0308 0309 // absl::StatusToStringMode is specified as a bitmask type, which means the 0310 // following operations must be provided: 0311 inline constexpr StatusToStringMode operator&(StatusToStringMode lhs, 0312 StatusToStringMode rhs) { 0313 return static_cast<StatusToStringMode>(static_cast<int>(lhs) & 0314 static_cast<int>(rhs)); 0315 } 0316 inline constexpr StatusToStringMode operator|(StatusToStringMode lhs, 0317 StatusToStringMode rhs) { 0318 return static_cast<StatusToStringMode>(static_cast<int>(lhs) | 0319 static_cast<int>(rhs)); 0320 } 0321 inline constexpr StatusToStringMode operator^(StatusToStringMode lhs, 0322 StatusToStringMode rhs) { 0323 return static_cast<StatusToStringMode>(static_cast<int>(lhs) ^ 0324 static_cast<int>(rhs)); 0325 } 0326 inline constexpr StatusToStringMode operator~(StatusToStringMode arg) { 0327 return static_cast<StatusToStringMode>(~static_cast<int>(arg)); 0328 } 0329 inline StatusToStringMode& operator&=(StatusToStringMode& lhs, 0330 StatusToStringMode rhs) { 0331 lhs = lhs & rhs; 0332 return lhs; 0333 } 0334 inline StatusToStringMode& operator|=(StatusToStringMode& lhs, 0335 StatusToStringMode rhs) { 0336 lhs = lhs | rhs; 0337 return lhs; 0338 } 0339 inline StatusToStringMode& operator^=(StatusToStringMode& lhs, 0340 StatusToStringMode rhs) { 0341 lhs = lhs ^ rhs; 0342 return lhs; 0343 } 0344 0345 // absl::Status 0346 // 0347 // The `absl::Status` class is generally used to gracefully handle errors 0348 // across API boundaries (and in particular across RPC boundaries). Some of 0349 // these errors may be recoverable, but others may not. Most 0350 // functions which can produce a recoverable error should be designed to return 0351 // either an `absl::Status` (or the similar `absl::StatusOr<T>`, which holds 0352 // either an object of type `T` or an error). 0353 // 0354 // API developers should construct their functions to return `absl::OkStatus()` 0355 // upon success, or an `absl::StatusCode` upon another type of error (e.g 0356 // an `absl::StatusCode::kInvalidArgument` error). The API provides convenience 0357 // functions to construct each status code. 0358 // 0359 // Example: 0360 // 0361 // absl::Status myFunction(absl::string_view fname, ...) { 0362 // ... 0363 // // encounter error 0364 // if (error condition) { 0365 // // Construct an absl::StatusCode::kInvalidArgument error 0366 // return absl::InvalidArgumentError("bad mode"); 0367 // } 0368 // // else, return OK 0369 // return absl::OkStatus(); 0370 // } 0371 // 0372 // Users handling status error codes should prefer checking for an OK status 0373 // using the `ok()` member function. Handling multiple error codes may justify 0374 // use of switch statement, but only check for error codes you know how to 0375 // handle; do not try to exhaustively match against all canonical error codes. 0376 // Errors that cannot be handled should be logged and/or propagated for higher 0377 // levels to deal with. If you do use a switch statement, make sure that you 0378 // also provide a `default:` switch case, so that code does not break as other 0379 // canonical codes are added to the API. 0380 // 0381 // Example: 0382 // 0383 // absl::Status result = DoSomething(); 0384 // if (!result.ok()) { 0385 // LOG(ERROR) << result; 0386 // } 0387 // 0388 // // Provide a default if switching on multiple error codes 0389 // switch (result.code()) { 0390 // // The user hasn't authenticated. Ask them to reauth 0391 // case absl::StatusCode::kUnauthenticated: 0392 // DoReAuth(); 0393 // break; 0394 // // The user does not have permission. Log an error. 0395 // case absl::StatusCode::kPermissionDenied: 0396 // LOG(ERROR) << result; 0397 // break; 0398 // // Propagate the error otherwise. 0399 // default: 0400 // return true; 0401 // } 0402 // 0403 // An `absl::Status` can optionally include a payload with more information 0404 // about the error. Typically, this payload serves one of several purposes: 0405 // 0406 // * It may provide more fine-grained semantic information about the error to 0407 // facilitate actionable remedies. 0408 // * It may provide human-readable contextual information that is more 0409 // appropriate to display to an end user. 0410 // 0411 // Example: 0412 // 0413 // absl::Status result = DoSomething(); 0414 // // Inform user to retry after 30 seconds 0415 // // See more error details in googleapis/google/rpc/error_details.proto 0416 // if (absl::IsResourceExhausted(result)) { 0417 // google::rpc::RetryInfo info; 0418 // info.retry_delay().seconds() = 30; 0419 // // Payloads require a unique key (a URL to ensure no collisions with 0420 // // other payloads), and an `absl::Cord` to hold the encoded data. 0421 // absl::string_view url = "type.googleapis.com/google.rpc.RetryInfo"; 0422 // result.SetPayload(url, info.SerializeAsCord()); 0423 // return result; 0424 // } 0425 // 0426 // For documentation see https://abseil.io/docs/cpp/guides/status. 0427 // 0428 // Returned Status objects may not be ignored. status_internal.h has a forward 0429 // declaration of the form 0430 // class ABSL_MUST_USE_RESULT Status; 0431 class ABSL_ATTRIBUTE_TRIVIAL_ABI Status final { 0432 public: 0433 // Constructors 0434 0435 // This default constructor creates an OK status with no message or payload. 0436 // Avoid this constructor and prefer explicit construction of an OK status 0437 // with `absl::OkStatus()`. 0438 Status(); 0439 0440 // Creates a status in the canonical error space with the specified 0441 // `absl::StatusCode` and error message. If `code == absl::StatusCode::kOk`, // NOLINT 0442 // `msg` is ignored and an object identical to an OK status is constructed. 0443 // 0444 // The `msg` string must be in UTF-8. The implementation may complain (e.g., // NOLINT 0445 // by printing a warning) if it is not. 0446 Status(absl::StatusCode code, absl::string_view msg); 0447 0448 Status(const Status&); 0449 Status& operator=(const Status& x); 0450 0451 // Move operators 0452 0453 // The moved-from state is valid but unspecified. 0454 Status(Status&&) noexcept; 0455 Status& operator=(Status&&) noexcept; 0456 0457 ~Status(); 0458 0459 // Status::Update() 0460 // 0461 // Updates the existing status with `new_status` provided that `this->ok()`. 0462 // If the existing status already contains a non-OK error, this update has no 0463 // effect and preserves the current data. Note that this behavior may change 0464 // in the future to augment a current non-ok status with additional 0465 // information about `new_status`. 0466 // 0467 // `Update()` provides a convenient way of keeping track of the first error 0468 // encountered. 0469 // 0470 // Example: 0471 // // Instead of "if (overall_status.ok()) overall_status = new_status" 0472 // overall_status.Update(new_status); 0473 // 0474 void Update(const Status& new_status); 0475 void Update(Status&& new_status); 0476 0477 // Status::ok() 0478 // 0479 // Returns `true` if `this->code()` == `absl::StatusCode::kOk`, 0480 // indicating the absence of an error. 0481 // Prefer checking for an OK status using this member function. 0482 ABSL_MUST_USE_RESULT bool ok() const; 0483 0484 // Status::code() 0485 // 0486 // Returns the canonical error code of type `absl::StatusCode` of this status. 0487 absl::StatusCode code() const; 0488 0489 // Status::raw_code() 0490 // 0491 // Returns a raw (canonical) error code corresponding to the enum value of 0492 // `google.rpc.Code` definitions within 0493 // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto. 0494 // These values could be out of the range of canonical `absl::StatusCode` 0495 // enum values. 0496 // 0497 // NOTE: This function should only be called when converting to an associated 0498 // wire format. Use `Status::code()` for error handling. 0499 int raw_code() const; 0500 0501 // Status::message() 0502 // 0503 // Returns the error message associated with this error code, if available. 0504 // Note that this message rarely describes the error code. It is not unusual 0505 // for the error message to be the empty string. As a result, prefer 0506 // `operator<<` or `Status::ToString()` for debug logging. 0507 absl::string_view message() const; 0508 0509 friend bool operator==(const Status&, const Status&); 0510 friend bool operator!=(const Status&, const Status&); 0511 0512 // Status::ToString() 0513 // 0514 // Returns a string based on the `mode`. By default, it returns combination of 0515 // the error code name, the message and any associated payload messages. This 0516 // string is designed simply to be human readable and its exact format should 0517 // not be load bearing. Do not depend on the exact format of the result of 0518 // `ToString()` which is subject to change. 0519 // 0520 // The printed code name and the message are generally substrings of the 0521 // result, and the payloads to be printed use the status payload printer 0522 // mechanism (which is internal). 0523 std::string ToString( 0524 StatusToStringMode mode = StatusToStringMode::kDefault) const; 0525 0526 // Support `absl::StrCat`, `absl::StrFormat`, etc. 0527 template <typename Sink> 0528 friend void AbslStringify(Sink& sink, const Status& status) { 0529 sink.Append(status.ToString(StatusToStringMode::kWithEverything)); 0530 } 0531 0532 // Status::IgnoreError() 0533 // 0534 // Ignores any errors. This method does nothing except potentially suppress 0535 // complaints from any tools that are checking that errors are not dropped on 0536 // the floor. 0537 void IgnoreError() const; 0538 0539 // swap() 0540 // 0541 // Swap the contents of one status with another. 0542 friend void swap(Status& a, Status& b) noexcept; 0543 0544 //---------------------------------------------------------------------------- 0545 // Payload Management APIs 0546 //---------------------------------------------------------------------------- 0547 0548 // A payload may be attached to a status to provide additional context to an 0549 // error that may not be satisfied by an existing `absl::StatusCode`. 0550 // Typically, this payload serves one of several purposes: 0551 // 0552 // * It may provide more fine-grained semantic information about the error 0553 // to facilitate actionable remedies. 0554 // * It may provide human-readable contextual information that is more 0555 // appropriate to display to an end user. 0556 // 0557 // A payload consists of a [key,value] pair, where the key is a string 0558 // referring to a unique "type URL" and the value is an object of type 0559 // `absl::Cord` to hold the contextual data. 0560 // 0561 // The "type URL" should be unique and follow the format of a URL 0562 // (https://en.wikipedia.org/wiki/URL) and, ideally, provide some 0563 // documentation or schema on how to interpret its associated data. For 0564 // example, the default type URL for a protobuf message type is 0565 // "type.googleapis.com/packagename.messagename". Other custom wire formats 0566 // should define the format of type URL in a similar practice so as to 0567 // minimize the chance of conflict between type URLs. 0568 // Users should ensure that the type URL can be mapped to a concrete 0569 // C++ type if they want to deserialize the payload and read it effectively. 0570 // 0571 // To attach a payload to a status object, call `Status::SetPayload()`, 0572 // passing it the type URL and an `absl::Cord` of associated data. Similarly, 0573 // to extract the payload from a status, call `Status::GetPayload()`. You 0574 // may attach multiple payloads (with differing type URLs) to any given 0575 // status object, provided that the status is currently exhibiting an error 0576 // code (i.e. is not OK). 0577 0578 // Status::GetPayload() 0579 // 0580 // Gets the payload of a status given its unique `type_url` key, if present. 0581 absl::optional<absl::Cord> GetPayload(absl::string_view type_url) const; 0582 0583 // Status::SetPayload() 0584 // 0585 // Sets the payload for a non-ok status using a `type_url` key, overwriting 0586 // any existing payload for that `type_url`. 0587 // 0588 // NOTE: This function does nothing if the Status is ok. 0589 void SetPayload(absl::string_view type_url, absl::Cord payload); 0590 0591 // Status::ErasePayload() 0592 // 0593 // Erases the payload corresponding to the `type_url` key. Returns `true` if 0594 // the payload was present. 0595 bool ErasePayload(absl::string_view type_url); 0596 0597 // Status::ForEachPayload() 0598 // 0599 // Iterates over the stored payloads and calls the 0600 // `visitor(type_key, payload)` callable for each one. 0601 // 0602 // NOTE: The order of calls to `visitor()` is not specified and may change at 0603 // any time. 0604 // 0605 // NOTE: Any mutation on the same 'absl::Status' object during visitation is 0606 // forbidden and could result in undefined behavior. 0607 void ForEachPayload( 0608 absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor) 0609 const; 0610 0611 private: 0612 friend Status CancelledError(); 0613 0614 // Creates a status in the canonical error space with the specified 0615 // code, and an empty error message. 0616 explicit Status(absl::StatusCode code); 0617 0618 // Underlying constructor for status from a rep_. 0619 explicit Status(uintptr_t rep) : rep_(rep) {} 0620 0621 static void Ref(uintptr_t rep); 0622 static void Unref(uintptr_t rep); 0623 0624 // REQUIRES: !ok() 0625 // Ensures rep is not inlined or shared with any other Status. 0626 static absl::Nonnull<status_internal::StatusRep*> PrepareToModify( 0627 uintptr_t rep); 0628 0629 // MSVC 14.0 limitation requires the const. 0630 static constexpr const char kMovedFromString[] = 0631 "Status accessed after move."; 0632 0633 static absl::Nonnull<const std::string*> EmptyString(); 0634 static absl::Nonnull<const std::string*> MovedFromString(); 0635 0636 // Returns whether rep contains an inlined representation. 0637 // See rep_ for details. 0638 static constexpr bool IsInlined(uintptr_t rep); 0639 0640 // Indicates whether this Status was the rhs of a move operation. See rep_ 0641 // for details. 0642 static constexpr bool IsMovedFrom(uintptr_t rep); 0643 static constexpr uintptr_t MovedFromRep(); 0644 0645 // Convert between error::Code and the inlined uintptr_t representation used 0646 // by rep_. See rep_ for details. 0647 static constexpr uintptr_t CodeToInlinedRep(absl::StatusCode code); 0648 static constexpr absl::StatusCode InlinedRepToCode(uintptr_t rep); 0649 0650 // Converts between StatusRep* and the external uintptr_t representation used 0651 // by rep_. See rep_ for details. 0652 static uintptr_t PointerToRep(status_internal::StatusRep* r); 0653 static absl::Nonnull<const status_internal::StatusRep*> RepToPointer( 0654 uintptr_t r); 0655 0656 static std::string ToStringSlow(uintptr_t rep, StatusToStringMode mode); 0657 0658 // Status supports two different representations. 0659 // - When the low bit is set it is an inlined representation. 0660 // It uses the canonical error space, no message or payload. 0661 // The error code is (rep_ >> 2). 0662 // The (rep_ & 2) bit is the "moved from" indicator, used in IsMovedFrom(). 0663 // - When the low bit is off it is an external representation. 0664 // In this case all the data comes from a heap allocated Rep object. 0665 // rep_ is a status_internal::StatusRep* pointer to that structure. 0666 uintptr_t rep_; 0667 0668 friend class status_internal::StatusRep; 0669 }; 0670 0671 // OkStatus() 0672 // 0673 // Returns an OK status, equivalent to a default constructed instance. Prefer 0674 // usage of `absl::OkStatus()` when constructing such an OK status. 0675 Status OkStatus(); 0676 0677 // operator<<() 0678 // 0679 // Prints a human-readable representation of `x` to `os`. 0680 std::ostream& operator<<(std::ostream& os, const Status& x); 0681 0682 // IsAborted() 0683 // IsAlreadyExists() 0684 // IsCancelled() 0685 // IsDataLoss() 0686 // IsDeadlineExceeded() 0687 // IsFailedPrecondition() 0688 // IsInternal() 0689 // IsInvalidArgument() 0690 // IsNotFound() 0691 // IsOutOfRange() 0692 // IsPermissionDenied() 0693 // IsResourceExhausted() 0694 // IsUnauthenticated() 0695 // IsUnavailable() 0696 // IsUnimplemented() 0697 // IsUnknown() 0698 // 0699 // These convenience functions return `true` if a given status matches the 0700 // `absl::StatusCode` error code of its associated function. 0701 ABSL_MUST_USE_RESULT bool IsAborted(const Status& status); 0702 ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status); 0703 ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status); 0704 ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status); 0705 ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status); 0706 ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status); 0707 ABSL_MUST_USE_RESULT bool IsInternal(const Status& status); 0708 ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status); 0709 ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status); 0710 ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status); 0711 ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status); 0712 ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status); 0713 ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status); 0714 ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status); 0715 ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status); 0716 ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status); 0717 0718 // AbortedError() 0719 // AlreadyExistsError() 0720 // CancelledError() 0721 // DataLossError() 0722 // DeadlineExceededError() 0723 // FailedPreconditionError() 0724 // InternalError() 0725 // InvalidArgumentError() 0726 // NotFoundError() 0727 // OutOfRangeError() 0728 // PermissionDeniedError() 0729 // ResourceExhaustedError() 0730 // UnauthenticatedError() 0731 // UnavailableError() 0732 // UnimplementedError() 0733 // UnknownError() 0734 // 0735 // These convenience functions create an `absl::Status` object with an error 0736 // code as indicated by the associated function name, using the error message 0737 // passed in `message`. 0738 Status AbortedError(absl::string_view message); 0739 Status AlreadyExistsError(absl::string_view message); 0740 Status CancelledError(absl::string_view message); 0741 Status DataLossError(absl::string_view message); 0742 Status DeadlineExceededError(absl::string_view message); 0743 Status FailedPreconditionError(absl::string_view message); 0744 Status InternalError(absl::string_view message); 0745 Status InvalidArgumentError(absl::string_view message); 0746 Status NotFoundError(absl::string_view message); 0747 Status OutOfRangeError(absl::string_view message); 0748 Status PermissionDeniedError(absl::string_view message); 0749 Status ResourceExhaustedError(absl::string_view message); 0750 Status UnauthenticatedError(absl::string_view message); 0751 Status UnavailableError(absl::string_view message); 0752 Status UnimplementedError(absl::string_view message); 0753 Status UnknownError(absl::string_view message); 0754 0755 // ErrnoToStatusCode() 0756 // 0757 // Returns the StatusCode for `error_number`, which should be an `errno` value. 0758 // See https://en.cppreference.com/w/cpp/error/errno_macros and similar 0759 // references. 0760 absl::StatusCode ErrnoToStatusCode(int error_number); 0761 0762 // ErrnoToStatus() 0763 // 0764 // Convenience function that creates a `absl::Status` using an `error_number`, 0765 // which should be an `errno` value. 0766 Status ErrnoToStatus(int error_number, absl::string_view message); 0767 0768 //------------------------------------------------------------------------------ 0769 // Implementation details follow 0770 //------------------------------------------------------------------------------ 0771 0772 inline Status::Status() : Status(absl::StatusCode::kOk) {} 0773 0774 inline Status::Status(absl::StatusCode code) : Status(CodeToInlinedRep(code)) {} 0775 0776 inline Status::Status(const Status& x) : Status(x.rep_) { Ref(rep_); } 0777 0778 inline Status& Status::operator=(const Status& x) { 0779 uintptr_t old_rep = rep_; 0780 if (x.rep_ != old_rep) { 0781 Ref(x.rep_); 0782 rep_ = x.rep_; 0783 Unref(old_rep); 0784 } 0785 return *this; 0786 } 0787 0788 inline Status::Status(Status&& x) noexcept : Status(x.rep_) { 0789 x.rep_ = MovedFromRep(); 0790 } 0791 0792 inline Status& Status::operator=(Status&& x) noexcept { 0793 uintptr_t old_rep = rep_; 0794 if (x.rep_ != old_rep) { 0795 rep_ = x.rep_; 0796 x.rep_ = MovedFromRep(); 0797 Unref(old_rep); 0798 } 0799 return *this; 0800 } 0801 0802 inline void Status::Update(const Status& new_status) { 0803 if (ok()) { 0804 *this = new_status; 0805 } 0806 } 0807 0808 inline void Status::Update(Status&& new_status) { 0809 if (ok()) { 0810 *this = std::move(new_status); 0811 } 0812 } 0813 0814 inline Status::~Status() { Unref(rep_); } 0815 0816 inline bool Status::ok() const { 0817 return rep_ == CodeToInlinedRep(absl::StatusCode::kOk); 0818 } 0819 0820 inline absl::StatusCode Status::code() const { 0821 return status_internal::MapToLocalCode(raw_code()); 0822 } 0823 0824 inline int Status::raw_code() const { 0825 if (IsInlined(rep_)) return static_cast<int>(InlinedRepToCode(rep_)); 0826 return static_cast<int>(RepToPointer(rep_)->code()); 0827 } 0828 0829 inline absl::string_view Status::message() const { 0830 return !IsInlined(rep_) 0831 ? RepToPointer(rep_)->message() 0832 : (IsMovedFrom(rep_) ? absl::string_view(kMovedFromString) 0833 : absl::string_view()); 0834 } 0835 0836 inline bool operator==(const Status& lhs, const Status& rhs) { 0837 if (lhs.rep_ == rhs.rep_) return true; 0838 if (Status::IsInlined(lhs.rep_)) return false; 0839 if (Status::IsInlined(rhs.rep_)) return false; 0840 return *Status::RepToPointer(lhs.rep_) == *Status::RepToPointer(rhs.rep_); 0841 } 0842 0843 inline bool operator!=(const Status& lhs, const Status& rhs) { 0844 return !(lhs == rhs); 0845 } 0846 0847 inline std::string Status::ToString(StatusToStringMode mode) const { 0848 return ok() ? "OK" : ToStringSlow(rep_, mode); 0849 } 0850 0851 inline void Status::IgnoreError() const { 0852 // no-op 0853 } 0854 0855 inline void swap(absl::Status& a, absl::Status& b) noexcept { 0856 using std::swap; 0857 swap(a.rep_, b.rep_); 0858 } 0859 0860 inline absl::optional<absl::Cord> Status::GetPayload( 0861 absl::string_view type_url) const { 0862 if (IsInlined(rep_)) return absl::nullopt; 0863 return RepToPointer(rep_)->GetPayload(type_url); 0864 } 0865 0866 inline void Status::SetPayload(absl::string_view type_url, absl::Cord payload) { 0867 if (ok()) return; 0868 status_internal::StatusRep* rep = PrepareToModify(rep_); 0869 rep->SetPayload(type_url, std::move(payload)); 0870 rep_ = PointerToRep(rep); 0871 } 0872 0873 inline bool Status::ErasePayload(absl::string_view type_url) { 0874 if (IsInlined(rep_)) return false; 0875 status_internal::StatusRep* rep = PrepareToModify(rep_); 0876 auto res = rep->ErasePayload(type_url); 0877 rep_ = res.new_rep; 0878 return res.erased; 0879 } 0880 0881 inline void Status::ForEachPayload( 0882 absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor) 0883 const { 0884 if (IsInlined(rep_)) return; 0885 RepToPointer(rep_)->ForEachPayload(visitor); 0886 } 0887 0888 constexpr bool Status::IsInlined(uintptr_t rep) { return (rep & 1) != 0; } 0889 0890 constexpr bool Status::IsMovedFrom(uintptr_t rep) { return (rep & 2) != 0; } 0891 0892 constexpr uintptr_t Status::CodeToInlinedRep(absl::StatusCode code) { 0893 return (static_cast<uintptr_t>(code) << 2) + 1; 0894 } 0895 0896 constexpr absl::StatusCode Status::InlinedRepToCode(uintptr_t rep) { 0897 ABSL_ASSERT(IsInlined(rep)); 0898 return static_cast<absl::StatusCode>(rep >> 2); 0899 } 0900 0901 constexpr uintptr_t Status::MovedFromRep() { 0902 return CodeToInlinedRep(absl::StatusCode::kInternal) | 2; 0903 } 0904 0905 inline absl::Nonnull<const status_internal::StatusRep*> Status::RepToPointer( 0906 uintptr_t rep) { 0907 assert(!IsInlined(rep)); 0908 return reinterpret_cast<const status_internal::StatusRep*>(rep); 0909 } 0910 0911 inline uintptr_t Status::PointerToRep( 0912 absl::Nonnull<status_internal::StatusRep*> rep) { 0913 return reinterpret_cast<uintptr_t>(rep); 0914 } 0915 0916 inline void Status::Ref(uintptr_t rep) { 0917 if (!IsInlined(rep)) RepToPointer(rep)->Ref(); 0918 } 0919 0920 inline void Status::Unref(uintptr_t rep) { 0921 if (!IsInlined(rep)) RepToPointer(rep)->Unref(); 0922 } 0923 0924 inline Status OkStatus() { return Status(); } 0925 0926 // Creates a `Status` object with the `absl::StatusCode::kCancelled` error code 0927 // and an empty message. It is provided only for efficiency, given that 0928 // message-less kCancelled errors are common in the infrastructure. 0929 inline Status CancelledError() { return Status(absl::StatusCode::kCancelled); } 0930 0931 // Retrieves a message's status as a null terminated C string. The lifetime of 0932 // this string is tied to the lifetime of the status object itself. 0933 // 0934 // If the status's message is empty, the empty string is returned. 0935 // 0936 // StatusMessageAsCStr exists for C support. Use `status.message()` in C++. 0937 absl::Nonnull<const char*> StatusMessageAsCStr( 0938 const Status& status ABSL_ATTRIBUTE_LIFETIME_BOUND); 0939 0940 ABSL_NAMESPACE_END 0941 } // namespace absl 0942 0943 #endif // ABSL_STATUS_STATUS_H_
[ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |
![]() ![]() |