Apache Mesos
errorbase.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_ERROR_BASE_HPP__
14 #define __STOUT_ERROR_BASE_HPP__
15 
16 #include <errno.h>
17 
18 #include <ostream>
19 #include <string>
20 
21 #include <stout/os/strerror.hpp>
22 
23 // A useful type that can be used to represent a Try that has
24 // failed. You can also use 'ErrnoError' to append the error message
25 // associated with the current 'errno' to your own error message.
26 //
27 // Examples:
28 //
29 // Result<int> result = Error("uninitialized");
30 // Try<std::string> = Error("uninitialized");
31 //
32 // void foo(Try<std::string> t) {}
33 //
34 // foo(Error("some error here"));
35 
36 class Error
37 {
38 public:
39  explicit Error(const std::string& _message) : message(_message) {}
40 
41  bool operator==(const Error& that) const
42  {
43  return message == that.message;
44  }
45 
46  const std::string message;
47 };
48 
49 
50 class ErrnoError : public Error
51 {
52 public:
53  ErrnoError() : ErrnoError(errno) {}
54 
55  explicit ErrnoError(int _code) : Error(os::strerror(_code)), code(_code) {}
56 
57  explicit ErrnoError(const std::string& message)
58  : ErrnoError(errno, message) {}
59 
60  ErrnoError(int _code, const std::string& message)
61  : Error(message + ": " + os::strerror(_code)), code(_code) {}
62 
63  const int code;
64 };
65 
66 
67 inline std::ostream& operator<<(std::ostream& stream, const Error& error)
68 {
69  return stream << error.message;
70 }
71 
72 #endif // __STOUT_ERROR_BASE_HPP__
std::string strerror(int errno_)
A thread-safe version of strerror.
Definition: strerror.hpp:30
Definition: errorbase.hpp:36
Error(const std::string &_message)
Definition: errorbase.hpp:39
ErrnoError(int _code, const std::string &message)
Definition: errorbase.hpp:60
Definition: errorbase.hpp:50
Definition: posix_signalhandler.hpp:23
ErrnoError(const std::string &message)
Definition: errorbase.hpp:57
ErrnoError()
Definition: errorbase.hpp:53
bool operator==(const Error &that) const
Definition: errorbase.hpp:41
std::ostream & operator<<(std::ostream &stream, const Error &error)
Definition: errorbase.hpp:67
const std::string message
Definition: errorbase.hpp:46
std::string error(const std::string &msg, uint32_t code)
const int code
Definition: errorbase.hpp:63
ErrnoError(int _code)
Definition: errorbase.hpp:55