From dadbd046f1e21f9d6ed27ba038130437b9e95595 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 14 Aug 2018 20:42:05 +0200 Subject: [PATCH 1/2] Don't crash when formatting in logging throws exceptions --- src/util.h | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/util.h b/src/util.h index 468613100e87..eb436f7f3689 100644 --- a/src/util.h +++ b/src/util.h @@ -94,20 +94,31 @@ bool LogAcceptCategory(const char* category); /** Send a string to the log output */ int LogPrintStr(const std::string &str); +/** Formats a string without throwing exceptions. Instead, it'll return an error string instead of formatted string. */ +template +std::string SafeStringFormat(const std::string& fmt, const Args&... args) +{ + try { + return tinyformat::format(fmt, args...); + } catch (std::runtime_error& e) { + return tinyformat::format("****TINYFORMAT ERROR**** - err=%s, fmt=%s", e.what(), fmt); + } +} + #define LogPrint(category, ...) do { \ if (LogAcceptCategory((category))) { \ - LogPrintStr(tinyformat::format(__VA_ARGS__)); \ + LogPrintStr(SafeStringFormat(__VA_ARGS__)); \ } \ } while(0) #define LogPrintf(...) do { \ - LogPrintStr(tinyformat::format(__VA_ARGS__)); \ + LogPrintStr(SafeStringFormat(__VA_ARGS__)); \ } while(0) template bool error(const char* fmt, const Args&... args) { - LogPrintStr("ERROR: " + tinyformat::format(fmt, args...) + "\n"); + LogPrintStr("ERROR: " + SafeStringFormat(fmt, args...) + "\n"); return false; } From 512d372210fb7db30b89c59938edb61777cc2c40 Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 21 Aug 2018 16:08:44 +0200 Subject: [PATCH 2/2] Preserve exception like output --- src/util.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/util.h b/src/util.h index eb436f7f3689..98c924328c62 100644 --- a/src/util.h +++ b/src/util.h @@ -101,7 +101,9 @@ std::string SafeStringFormat(const std::string& fmt, const Args&... args) try { return tinyformat::format(fmt, args...); } catch (std::runtime_error& e) { - return tinyformat::format("****TINYFORMAT ERROR**** - err=%s, fmt=%s", e.what(), fmt); + std::string message = tinyformat::format("\n****TINYFORMAT ERROR****\n err=\"%s\"\n fmt=\"%s\"\n", e.what(), fmt); + fprintf(stderr, "%s", message.c_str()); + return message; } }