From 3b0fa7dd190d6cc2253e2b10f96058a3d42f90ff Mon Sep 17 00:00:00 2001 From: Dup4 Date: Sun, 2 Jul 2023 13:10:25 +0800 Subject: [PATCH 1/2] feat: support chaincall for handle error Signed-off-by: Dup4 --- include/result/result.h | 8 ++++++-- test/result_test.cc | 22 +++++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/include/result/result.h b/include/result/result.h index 8e2db93..aedec1b 100644 --- a/include/result/result.h +++ b/include/result/result.h @@ -143,17 +143,21 @@ class Result { } template - void NotOKThen(F&& f) { + R& NotOKThen(F&& f) { if (IsOK()) { return; } f(*this); + + return static_cast(*this); } template - void AlwaysThen(F&& f) { + R& AlwaysThen(F&& f) { f(*this); + + return static_cast(*this); } void PushHistory(const std::string& file_name, int32_t line) { diff --git a/test/result_test.cc b/test/result_test.cc index df891c4..1a20f0c 100644 --- a/test/result_test.cc +++ b/test/result_test.cc @@ -384,7 +384,7 @@ TEST_F(ResultTest, smart_pointer_with_nullptr) { } } -TEST_F(ResultTest, NotOKThen) { +TEST_F(ResultTest, NotOKThenAndAlwaysThen) { int flag = 0; std::invoke([]() -> CustomResult { @@ -418,6 +418,26 @@ TEST_F(ResultTest, NotOKThen) { }); EXPECT_EQ(flag, 3); + + { + int n_flag = 0; + int a_flag = 0; + + std::invoke([]() -> CustomResult { + return CustomResult::Builder(CustomResult::ErrorCode::OtherError).Build(); + }) + .NotOKThen([&n_flag](auto&& res) { + EXPECT_FALSE(res.IsOK()); + n_flag = 1; + }) + .AlwaysThen([&a_flag](auto&& res) { + EXPECT_FALSE(res.IsOK()); + a_flag = 1; + }); + + EXPECT_EQ(n_flag, 1); + EXPECT_EQ(a_flag, 1); + } } TEST_F(ResultTest, GetHistoryInfoNode) { From 19743fc72aa4a7b356d201e726a65a7c927c6873 Mon Sep 17 00:00:00 2001 From: Dup4 Date: Sun, 2 Jul 2023 13:14:16 +0800 Subject: [PATCH 2/2] fix: return value Signed-off-by: Dup4 --- include/result/result.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/result/result.h b/include/result/result.h index aedec1b..cf47fb2 100644 --- a/include/result/result.h +++ b/include/result/result.h @@ -145,7 +145,7 @@ class Result { template R& NotOKThen(F&& f) { if (IsOK()) { - return; + return static_cast(*this); } f(*this);