Skip to content

Commit

Permalink
Include file:line information in CHECK_THROW to aid troubleshooting
Browse files Browse the repository at this point in the history
Summary: see title

Reviewed By: yfeldblum

Differential Revision: D69070237

fbshipit-source-id: 28f5dfea8934e98dbb0f6f31314eaf85d561a913
  • Loading branch information
Stefan Larimore authored and facebook-github-bot committed Feb 5, 2025
1 parent 9d0b066 commit d653344
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
12 changes: 7 additions & 5 deletions folly/Exception.h
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,13 @@ void checkFopenErrorExplicit(FILE* fp, int savedErrno, Args&&... args) {
* If cond is not true, raise an exception of type E. E must have a ctor that
* works with const char* (a description of the failure).
*/
#define CHECK_THROW(cond, E) \
do { \
if (!(cond)) { \
folly::throw_exception<E>("Check failed: " #cond); \
} \
#define CHECK_THROW(cond, E) \
do { \
if (!(cond)) { \
folly::throw_exception<E>( \
"Check failed: " #cond ", in " __FILE__ \
":" FOLLY_PP_STRINGIZE_MACRO(__LINE__)); \
} \
} while (0)

} // namespace folly
7 changes: 7 additions & 0 deletions folly/Preprocessor.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@
*/
#define FOLLY_PP_STRINGIZE(x) #x

/**
* Use FOLLY_PP_STRINGIZE_MACRO(x) when you want the string representation
* of a non-string c++ preprocessing macro value, ex
* FOLLY_PP_STRINGIZE_MACRO(__LINE__).
*/
#define FOLLY_PP_STRINGIZE_MACRO(x) FOLLY_PP_STRINGIZE(x)

#define FOLLY_PP_DETAIL_NARGS_1( \
dummy, \
_15, \
Expand Down
18 changes: 18 additions & 0 deletions folly/test/ExceptionTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,5 +121,23 @@ TEST(ExceptionTest, makeSystemError) {
<< "what() string missing input message: " << ex.what();
}

TEST(ExceptionTest, testCheckThrow) {
auto throwIf = [](bool shouldThrow) {
CHECK_THROW(!shouldThrow, std::runtime_error);
};
EXPECT_NO_THROW(throwIf(false));
EXPECT_THROW(throwIf(true), std::runtime_error);

try {
throwIf(true);
} catch (const std::runtime_error& e) {
auto msg = std::string(e.what());
EXPECT_TRUE(msg.find("Check failed: !shouldThrow") != std::string::npos);
EXPECT_TRUE(msg.find("folly/test/ExceptionTest.cpp") != std::string::npos);
auto lineNumber = msg.substr(msg.rfind(':') + 1);
EXPECT_TRUE(std::all_of(lineNumber.begin(), lineNumber.end(), ::isdigit));
}
}

} // namespace test
} // namespace folly

0 comments on commit d653344

Please sign in to comment.