Skip to content

Commit 3b092bd

Browse files
committed
util: Properly handle errors during log message formatting
Instead of having an exception propagate into the program when an error happens while formatting a log message, just print a message to the log. Addresses #9423.
1 parent e3e7db8 commit 3b092bd

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/util.h

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,24 @@ bool LogAcceptCategory(const char* category);
7373
/** Send a string to the log output */
7474
int LogPrintStr(const std::string &str);
7575

76-
#define LogPrint(category, ...) do { \
77-
if (LogAcceptCategory((category))) { \
78-
LogPrintStr(tfm::format(__VA_ARGS__)); \
76+
/** Get format string from VA_ARGS for error reporting */
77+
template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
78+
79+
#define LogPrintf(...) do { \
80+
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
81+
try { \
82+
_log_msg_ = tfm::format(__VA_ARGS__); \
83+
} catch (std::runtime_error &e) { \
84+
/* Original format string will have newline so don't add one here */ \
85+
_log_msg_ = "Error \"" + std::string(e.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
7986
} \
87+
LogPrintStr(_log_msg_); \
8088
} while(0)
8189

82-
#define LogPrintf(...) do { \
83-
LogPrintStr(tfm::format(__VA_ARGS__)); \
90+
#define LogPrint(category, ...) do { \
91+
if (LogAcceptCategory((category))) { \
92+
LogPrintf(__VA_ARGS__); \
93+
} \
8494
} while(0)
8595

8696
template<typename... Args>

0 commit comments

Comments
 (0)