2 * Copyright 2013 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_EXCEPTION_H_
18 #define FOLLY_EXCEPTION_H_
23 #include <system_error>
25 #include "folly/Conv.h"
26 #include "folly/Likely.h"
30 // Helper to throw std::system_error
31 void throwSystemError(int err, const char* msg) __attribute__((noreturn));
32 inline void throwSystemError(int err, const char* msg) {
33 throw std::system_error(err, std::system_category(), msg);
36 // Helper to throw std::system_error from errno
37 void throwSystemError(const char* msg) __attribute__((noreturn));
38 inline void throwSystemError(const char* msg) {
39 throwSystemError(errno, msg);
42 // Helper to throw std::system_error from errno and components of a string
43 template <class... Args>
44 void throwSystemError(Args... args) __attribute__((noreturn));
45 template <class... Args>
46 inline void throwSystemError(Args... args) {
47 throwSystemError(errno, folly::to<std::string>(args...));
50 // Check a Posix return code (0 on success, error number on error), throw
52 inline void checkPosixError(int err, const char* msg) {
53 if (UNLIKELY(err != 0)) {
54 throwSystemError(err, msg);
58 // Check a Linux kernel-style return code (>= 0 on success, negative error
59 // number on error), throw on error.
60 inline void checkKernelError(ssize_t ret, const char* msg) {
61 if (UNLIKELY(ret < 0)) {
62 throwSystemError(-ret, msg);
66 // Check a traditional Unix return code (-1 and sets errno on error), throw
68 inline void checkUnixError(ssize_t ret, const char* msg) {
69 if (UNLIKELY(ret == -1)) {
70 throwSystemError(msg);
73 inline void checkUnixError(ssize_t ret, int savedErrno, const char* msg) {
74 if (UNLIKELY(ret == -1)) {
75 throwSystemError(savedErrno, msg);
81 #endif /* FOLLY_EXCEPTION_H_ */