Skip to content

Commit 8040ae6

Browse files
committed
Merge #9963: util: Properly handle errors during log message formatting
b651270 util: Throw tinyformat::format_error on formatting error (Wladimir J. van der Laan) 3b092bd util: Properly handle errors during log message formatting (Wladimir J. van der Laan) Tree-SHA512: 85e3b7afec2255fc88034187f1abd6060e9421de17ed4e3d918416f393429a99cc2c974b362099aaaff6970549df47664bea4c857c4e46acc0789663201dc541
2 parents fa99663 + b651270 commit 8040ae6

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

src/tinyformat.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ namespace tinyformat {}
123123
namespace tfm = tinyformat;
124124

125125
// Error handling; calls assert() by default.
126-
#define TINYFORMAT_ERROR(reasonString) throw std::runtime_error(reasonString)
126+
#define TINYFORMAT_ERROR(reasonString) throw tinyformat::format_error(reasonString)
127127

128128
// Define for C++11 variadic templates which make the code shorter & more
129129
// general. If you don't define this, C++11 support is autodetected below.
@@ -164,6 +164,13 @@ namespace tfm = tinyformat;
164164

165165
namespace tinyformat {
166166

167+
class format_error: public std::runtime_error
168+
{
169+
public:
170+
format_error(const std::string &what): std::runtime_error(what) {
171+
}
172+
};
173+
167174
//------------------------------------------------------------------------------
168175
namespace detail {
169176

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 (tinyformat::format_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)