Skip to content

Commit 67eb699

Browse files
committed
util: Properly handle errors during log message formatting
backports bitcoin/bitcoin@3b092bd
1 parent 66ec97b commit 67eb699

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/util.h

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,24 @@ bool LogAcceptCategory(const char* category);
6262
/** Send a string to the log output */
6363
int LogPrintStr(const std::string& str);
6464

65-
#define LogPrint(category, ...) do { \
66-
if (LogAcceptCategory((category))) { \
67-
LogPrintStr(tfm::format(__VA_ARGS__)); \
68-
} \
65+
/** Get format string from VA_ARGS for error reporting */
66+
template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
67+
68+
#define LogPrintf(...) do { \
69+
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
70+
try { \
71+
_log_msg_ = tfm::format(__VA_ARGS__); \
72+
} catch (std::runtime_error &e) { \
73+
/* Original format string will have newline so don't add one here */ \
74+
_log_msg_ = "Error \"" + std::string(e.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
75+
} \
76+
LogPrintStr(_log_msg_); \
6977
} while(0)
7078

71-
#define LogPrintf(...) do { \
72-
LogPrintStr(tfm::format(__VA_ARGS__)); \
79+
#define LogPrint(category, ...) do { \
80+
if (LogAcceptCategory((category))) { \
81+
LogPrintf(__VA_ARGS__); \
82+
} \
7383
} while(0)
7484

7585
template<typename... Args>

0 commit comments

Comments
 (0)