AsyncIO in folly
[folly.git] / folly / Exception.h
1 /*
2  * Copyright 2013 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 #ifndef FOLLY_EXCEPTION_H_
18 #define FOLLY_EXCEPTION_H_
19
20 #include <errno.h>
21
22 #include <stdexcept>
23 #include <system_error>
24
25 #include "folly/Likely.h"
26
27 namespace folly {
28
29 // Helper to throw std::system_error
30 void throwSystemError(int err, const char* msg) __attribute__((noreturn));
31 inline void throwSystemError(int err, const char* msg) {
32   throw std::system_error(err, std::system_category(), msg);
33 }
34
35 // Helper to throw std::system_error from errno
36 void throwSystemError(const char* msg) __attribute__((noreturn));
37 inline void throwSystemError(const char* msg) {
38   throwSystemError(errno, msg);
39 }
40
41 // Check a Posix return code (0 on success, error number on error), throw
42 // on error.
43 inline void checkPosixError(int err, const char* msg) {
44   if (UNLIKELY(err != 0)) {
45     throwSystemError(err, msg);
46   }
47 }
48
49 // Check a Linux kernel-style return code (>= 0 on success, negative error
50 // number on error), throw on error.
51 inline void checkKernelError(ssize_t ret, const char* msg) {
52   if (UNLIKELY(ret < 0)) {
53     throwSystemError(-ret, msg);
54   }
55 }
56
57 // Check a traditional Uinx return code (-1 and sets errno on error), throw
58 // on error.
59 inline void checkUnixError(ssize_t ret, const char* msg) {
60   if (UNLIKELY(ret == -1)) {
61     throwSystemError(msg);
62   }
63 }
64 inline void checkUnixError(ssize_t ret, int savedErrno, const char* msg) {
65   if (UNLIKELY(ret == -1)) {
66     throwSystemError(savedErrno, msg);
67   }
68 }
69
70 }  // namespace folly
71
72 #endif /* FOLLY_EXCEPTION_H_ */
73