Skip to content

Commit

Permalink
labm8/cpp: Add a Status.RaiseException() method.
Browse files Browse the repository at this point in the history
This converts the error code into my best guess at the most
appropriate C++ exception class, and raises it. If status.ok(), no
error is raised.

Signed-off-by: format 2020.01.16 <github.com/ChrisCummins/format>
  • Loading branch information
ChrisCummins committed Mar 18, 2020
1 parent 8c822a3 commit 99c1e71
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
30 changes: 30 additions & 0 deletions labm8/cpp/status.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include "labm8/cpp/stringpiece.h"

#include <iosfwd>
#include <stdexcept>
#include <string>

namespace labm8 {
Expand Down Expand Up @@ -91,6 +92,35 @@ class Status {
// Return a combination of the error code name and message.
string ToString() const;

// Raise an error if !this->ok().
void RaiseException() const {
if (!ok()) {
switch (error_code()) {
case error::Code::CANCELLED:
case error::Code::UNKNOWN:
case error::Code::DEADLINE_EXCEEDED:
case error::Code::NOT_FOUND:
case error::Code::ALREADY_EXISTS:
case error::Code::PERMISSION_DENIED:
case error::Code::UNAUTHENTICATED:
case error::Code::RESOURCE_EXHAUSTED:
case error::Code::ABORTED:
case error::Code::INTERNAL:
case error::Code::UNAVAILABLE:
case error::Code::DATA_LOSS:
throw std::runtime_error(error_message());
case error::Code::INVALID_ARGUMENT:
case error::Code::FAILED_PRECONDITION:
throw std::invalid_argument(error_message());
case error::Code::OUT_OF_RANGE:
throw std::out_of_range(error_message());
case error::Code::UNIMPLEMENTED:
case error::Code::OK:
throw std::logic_error(error_message());
}
}
}

private:
error::Code error_code_;
std::string error_message_;
Expand Down
6 changes: 1 addition & 5 deletions labm8/cpp/statusor.h
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ class StatusOr {

// Returns a reference to our current value, or raises an exception
// if !this->ok().
template <typename Error = std::runtime_error>
const T &ValueOrException() const;

private:
Expand Down Expand Up @@ -253,11 +252,8 @@ inline const T &StatusOr<T>::ValueOrDie() const {
}

template <typename T>
template <typename Error>
inline const T &StatusOr<T>::ValueOrException() const {
if (!status_.ok()) {
throw Error(status_.ToString());
}
status_.RaiseException();
return value_;
}

Expand Down

0 comments on commit 99c1e71

Please sign in to comment.