diff --git a/error/CMakeLists.txt b/error/CMakeLists.txt index ae7f826..379da05 100644 --- a/error/CMakeLists.txt +++ b/error/CMakeLists.txt @@ -5,11 +5,14 @@ project(error) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wnon-virtual-dtor -Wpedantic") set(CMAKE_CXX_STANDARD 11) +include(cmake/CPM.cmake) +cpmaddpackage("gh:fmtlib/fmt#10.0.0") + add_library(error src/error.cpp) target_include_directories(error PUBLIC include) +target_link_libraries(error PUBLIC fmt) if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - include(cmake/CPM.cmake) cpmaddpackage("gh:TheLartians/Format.cmake@1.7.3") if(BUILD_TESTING) diff --git a/error/include/error/error.hpp b/error/include/error/error.hpp index bd70762..eba1c39 100644 --- a/error/include/error/error.hpp +++ b/error/include/error/error.hpp @@ -1,6 +1,10 @@ #pragma once +#include + #include +#include +#include namespace error { @@ -9,14 +13,18 @@ namespace error { */ class Error : public std::exception { private: - const char* message; /**< The error message. */ + std::string message; /**< The error message. */ public: /** - * @brief Constructs a new error with the given message. - * @param message An error message. + * @brief Constructs a new error with the given format for the message. + * @tparam T Variadic template parameter pack for format arguments. + * @param fmt A format string for the message. + * @param args Format arguments. */ - Error(const char* message); + template + Error(fmt::format_string fmt, T&&... args) + : message(fmt::format(fmt, std::forward(args)...)) {} /** * @brief Returns the explanatory string. diff --git a/error/src/error.cpp b/error/src/error.cpp index 0c2d874..6d6310e 100644 --- a/error/src/error.cpp +++ b/error/src/error.cpp @@ -2,8 +2,6 @@ namespace error { -Error::Error(const char* message) : message(message) {} - -const char* Error::what() const noexcept { return message; } +const char* Error::what() const noexcept { return message.c_str(); } } // namespace error diff --git a/error/test/error_test.cpp b/error/test/error_test.cpp index 3afb818..f1c7755 100644 --- a/error/test/error_test.cpp +++ b/error/test/error_test.cpp @@ -3,8 +3,15 @@ #include TEST_CASE("Error Construction") { - const error::Error err("unknown error"); - REQUIRE(std::string("unknown error") == err.what()); + SECTION("With one argument") { + const error::Error err("unknown error"); + REQUIRE(std::string("unknown error") == err.what()); + } + + SECTION("With one or more arguments") { + const error::Error err("HTTP error {}", 404); + REQUIRE(std::string("HTTP error 404") == err.what()); + } } TEST_CASE("Error Throwing and Catching") {