Skip to content

Commit ca30622

Browse files
committed
feat(error): modify Error constructor to format message using {fmt}
1 parent de34628 commit ca30622

File tree

4 files changed

+22
-8
lines changed

4 files changed

+22
-8
lines changed

error/CMakeLists.txt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@ project(error)
55
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wnon-virtual-dtor -Wpedantic")
66
set(CMAKE_CXX_STANDARD 11)
77

8+
include(cmake/CPM.cmake)
9+
cpmaddpackage("gh:fmtlib/fmt#10.0.0")
10+
811
add_library(error src/error.cpp)
912
target_include_directories(error PUBLIC include)
13+
target_link_libraries(error PUBLIC fmt)
1014

1115
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
12-
include(cmake/CPM.cmake)
1316
cpmaddpackage("gh:TheLartians/Format.cmake@1.7.3")
1417

1518
if(BUILD_TESTING)

error/include/error/error.hpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
#pragma once
22

3+
#include <fmt/core.h>
4+
35
#include <exception>
46
#include <string>
7+
#include <utility>
58

69
namespace error {
710

@@ -14,10 +17,13 @@ class Error : public std::exception {
1417

1518
public:
1619
/**
17-
* @brief Constructs a new error with the given message.
18-
* @param message An error message.
20+
* @brief Constructs a new error with the given format for the message.
21+
* @param fmt A format string for the message.
22+
* @param args Format arguments.
1923
*/
20-
Error(const char* message);
24+
template <typename... T>
25+
Error(fmt::format_string<T...> fmt, T&&... args)
26+
: message(fmt::format(fmt, std::forward<T>(args)...)) {}
2127

2228
/**
2329
* @brief Returns the explanatory string.

error/src/error.cpp

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
namespace error {
44

5-
Error::Error(const char* message) : message(message) {}
6-
75
const char* Error::what() const noexcept { return message.c_str(); }
86

97
} // namespace error

error/test/error_test.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,15 @@
33
#include <string>
44

55
TEST_CASE("Error Construction") {
6-
const error::Error err("unknown error");
7-
REQUIRE(std::string("unknown error") == err.what());
6+
SECTION("With one argument") {
7+
const error::Error err("unknown error");
8+
REQUIRE(std::string("unknown error") == err.what());
9+
}
10+
11+
SECTION("With one or more arguments") {
12+
const error::Error err("HTTP error {}", 404);
13+
REQUIRE(std::string("HTTP error 404") == err.what());
14+
}
815
}
916

1017
TEST_CASE("Error Throwing and Catching") {

0 commit comments

Comments
 (0)