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 <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12738
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
Tested-by: jenkins <jenkins@lttng.org>
*/
#include <fstream>
+#include "logging.hpp"
+
#include "exc.hpp"
#include "file-utils.hpp"
namespace bt2c {
-std::vector<std::uint8_t> dataFromFile(const char * const filePath)
+std::vector<std::uint8_t> 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
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 {};
}
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<std::uint8_t> dataFromFile(const char *path);
+std::vector<std::uint8_t> dataFromFile(const char *path, const Logger& logger, bool fatalError);
} /* namespace bt2c */