status.cc
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #include "util/status.h"
5 
6 #include "base/logging.h"
7 
8 using std::string;
9 
10 namespace util {
11 
12 const Status Status::CANCELLED(StatusCode::CANCELLED, "Cancelled");
13 const Status Status::OK;
14 
15 void Status::AddErrorMsg(StatusCode::Code code, const std::string& msg) {
16  if (!error_detail_) {
17  error_detail_.reset(new ErrorDetail{code, msg});
18  } else {
19  error_detail_->error_msgs.push_back(msg);
20  }
21  VLOG(2) << msg;
22 }
23 
24 void Status::AddErrorMsg(const std::string& msg) { AddErrorMsg(StatusCode::INTERNAL_ERROR, msg); }
25 
26 void Status::AddError(const Status& status) {
27  if (status.ok())
28  return;
29  AddErrorMsg(status.code(), status.ToString());
30 }
31 
32 void Status::GetErrorMsgs(std::vector<string>* msgs) const {
33  msgs->clear();
34  if (error_detail_ != NULL) {
35  *msgs = error_detail_->error_msgs;
36  }
37 }
38 
39 void Status::GetErrorMsg(string* msg) const {
40  msg->clear();
41  if (error_detail_ != NULL) {
42  if (StatusCode::Code_IsValid(error_detail_->error_code)) {
43  const string& str = StatusCode::Code_Name(error_detail_->error_code);
44  msg->append(str).append(" ");
45  }
46  for (const string& e : error_detail_->error_msgs) {
47  msg->append(e).append("\n");
48  }
49  if (!error_detail_->error_msgs.empty()) {
50  msg->pop_back();
51  }
52  } else {
53  msg->assign("OK");
54  }
55 }
56 
57 std::ostream& operator<<(std::ostream& o, const Status& status) {
58  o << status.ToString();
59  return o;
60 }
61 
62 namespace detail {
63 
64 bool StatusFailPrintImpl(const Status& st) {
65  LOG_IF(ERROR, !st.ok()) << "Status error " << st;
66 
67  return !st.ok();
68 }
69 
70 void PrintFatal(const char* file, unsigned line_num, const Status& st) {
71  string msg = st.ToString();
72  ::google::LogMessage{file, int(line_num), google::GLOG_FATAL}.stream() << msg;
73 }
74 
75 } // namespace detail
76 
77 } // namespace util