Move AsyncSocket to folly (try 2)
[folly.git] / folly / io / async / AsyncSocketException.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <folly/io/async/DelayedDestruction.h>
20
21 namespace folly {
22
23 class AsyncSocketException : public std::runtime_error {
24  public:
25   enum AsyncSocketExceptionType
26   { UNKNOWN = 0
27   , NOT_OPEN = 1
28   , ALREADY_OPEN = 2
29   , TIMED_OUT = 3
30   , END_OF_FILE = 4
31   , INTERRUPTED = 5
32   , BAD_ARGS = 6
33   , CORRUPTED_DATA = 7
34   , INTERNAL_ERROR = 8
35   , NOT_SUPPORTED = 9
36   , INVALID_STATE = 10
37   , SSL_ERROR = 12
38   , COULD_NOT_BIND = 13
39   , SASL_HANDSHAKE_TIMEOUT = 14
40   };
41
42   AsyncSocketException(
43     AsyncSocketExceptionType type, const std::string& message) :
44       std::runtime_error(message),
45       type_(type), errno_(0) {}
46
47   /** Error code */
48   AsyncSocketExceptionType type_;
49
50   /** A copy of the errno. */
51   int errno_;
52
53   AsyncSocketException(AsyncSocketExceptionType type,
54                       const std::string& message,
55                       int errno_copy) :
56       std::runtime_error(getMessage(message, errno_copy)),
57       type_(type), errno_(errno_copy) {}
58
59   AsyncSocketExceptionType getType() const noexcept { return type_; }
60   int getErrno() const noexcept { return errno_; }
61
62  protected:
63   /** Just like strerror_r but returns a C++ string object. */
64   std::string strerror_s(int errno_copy) {
65     return "errno = " + folly::to<std::string>(errno_copy);
66   }
67
68   /** Return a message based on the input. */
69   std::string getMessage(const std::string &message,
70                                 int errno_copy) {
71     if (errno_copy != 0) {
72       return message + ": " + strerror_s(errno_copy);
73     } else {
74       return message;
75     }
76   }
77 };
78
79 } // folly