1 // Copyright 2020 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 #include "absl/status/statusor.h"
15 
16 #include <cstdlib>
17 #include <utility>
18 
19 #include "absl/base/internal/raw_logging.h"
20 #include "absl/status/status.h"
21 #include "absl/strings/str_cat.h"
22 
23 namespace absl {
24 ABSL_NAMESPACE_BEGIN
25 
BadStatusOrAccess(absl::Status status)26 BadStatusOrAccess::BadStatusOrAccess(absl::Status status)
27     : status_(std::move(status)) {}
28 
29 BadStatusOrAccess::~BadStatusOrAccess() = default;
what() const30 const char* BadStatusOrAccess::what() const noexcept {
31   return "Bad StatusOr access";
32 }
33 
status() const34 const absl::Status& BadStatusOrAccess::status() const { return status_; }
35 
36 namespace internal_statusor {
37 
HandleInvalidStatusCtorArg(absl::Status * status)38 void Helper::HandleInvalidStatusCtorArg(absl::Status* status) {
39   const char* kMessage =
40       "An OK status is not a valid constructor argument to StatusOr<T>";
41 #ifdef NDEBUG
42   ABSL_INTERNAL_LOG(ERROR, kMessage);
43 #else
44   ABSL_INTERNAL_LOG(FATAL, kMessage);
45 #endif
46   // In optimized builds, we will fall back to InternalError.
47   *status = absl::InternalError(kMessage);
48 }
49 
Crash(const absl::Status & status)50 void Helper::Crash(const absl::Status& status) {
51   ABSL_INTERNAL_LOG(
52       FATAL,
53       absl::StrCat("Attempting to fetch value instead of handling error ",
54                    status.ToString()));
55 }
56 
ThrowBadStatusOrAccess(absl::Status status)57 void ThrowBadStatusOrAccess(absl::Status status) {
58 #ifdef ABSL_HAVE_EXCEPTIONS
59   throw absl::BadStatusOrAccess(std::move(status));
60 #else
61   ABSL_INTERNAL_LOG(
62       FATAL,
63       absl::StrCat("Attempting to fetch value instead of handling error ",
64                    status.ToString()));
65   std::abort();
66 #endif
67 }
68 
69 }  // namespace internal_statusor
70 ABSL_NAMESPACE_END
71 }  // namespace absl
72