From: Simon Marchi Date: Thu, 25 Apr 2024 14:57:24 +0000 (+0000) Subject: cpp-common/bt2c: optionally log and append errors in `dataFromFile()` X-Git-Url: http://drtracing.org/?a=commitdiff_plain;h=0f781e0b2c6b88ec2b4db7cbd288f31f1e7515fb;p=babeltrace.git cpp-common/bt2c: optionally log and append errors in `dataFromFile()` For some callers, a `dataFromFile()` error (`NoSuchFileOrDirectoryError` typically) may be fatal, in which case it would be appropriate to log an error and append an error cause. For others callers, it might not be fatal, they just want to catch the exception and carry on. To accomodate this, pass a logger to `dataFromFile()` and add a `fatalError` boolean parameter. Log an error and append an error cause on error if `fatalError` is true. Otherwise, log at the debug level. Change-Id: Id32639b16a928195bc430c1a2ce7671ced2ad43b Signed-off-by: Simon Marchi Reviewed-on: https://review.lttng.org/c/babeltrace/+/12738 Reviewed-by: Philippe Proulx Tested-by: jenkins --- diff --git a/src/cpp-common/bt2c/file-utils.cpp b/src/cpp-common/bt2c/file-utils.cpp index 93520182..de5e3e19 100644 --- a/src/cpp-common/bt2c/file-utils.cpp +++ b/src/cpp-common/bt2c/file-utils.cpp @@ -6,12 +6,15 @@ */ #include +#include "logging.hpp" + #include "exc.hpp" #include "file-utils.hpp" namespace bt2c { -std::vector dataFromFile(const char * const filePath) +std::vector dataFromFile(const char * const filePath, const Logger& logger, + const bool fatalError) { /* * Open a file stream and seek to the end of the stream to compute the size @@ -20,6 +23,14 @@ std::vector dataFromFile(const char * const filePath) std::ifstream file {filePath, std::ios::binary | std::ios::ate}; if (!file) { + constexpr const char *msg = "No such file or directory: path=\"{}\""; + + if (fatalError) { + BT_CPPLOGE_APPEND_CAUSE_SPEC(logger, msg, filePath); + } else { + BT_CPPLOGD_SPEC(logger, msg, filePath); + } + throw NoSuchFileOrDirectoryError {}; } diff --git a/src/cpp-common/bt2c/file-utils.hpp b/src/cpp-common/bt2c/file-utils.hpp index 17bbe8c3..9193d12e 100644 --- a/src/cpp-common/bt2c/file-utils.hpp +++ b/src/cpp-common/bt2c/file-utils.hpp @@ -12,10 +12,17 @@ namespace bt2c { +class Logger; + /* * Returns a vector of all the bytes contained in `path`. + * + * Throws `NoSuchFileOrDirectoryError` if the file does not exist. + * + * If `fatalError` is true, log an error and appends an error + * cause prior to throwing. Otherwise, log at the debug level. */ -std::vector dataFromFile(const char *path); +std::vector dataFromFile(const char *path, const Logger& logger, bool fatalError); } /* namespace bt2c */