Skip to content

Commit 3b0fa7d

Browse files
committed
feat: support chaincall for handle error
Signed-off-by: Dup4 <[email protected]>
1 parent 56d6287 commit 3b0fa7d

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

include/result/result.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,17 +143,21 @@ class Result {
143143
}
144144

145145
template <typename F>
146-
void NotOKThen(F&& f) {
146+
R& NotOKThen(F&& f) {
147147
if (IsOK()) {
148148
return;
149149
}
150150

151151
f(*this);
152+
153+
return static_cast<R&>(*this);
152154
}
153155

154156
template <typename F>
155-
void AlwaysThen(F&& f) {
157+
R& AlwaysThen(F&& f) {
156158
f(*this);
159+
160+
return static_cast<R&>(*this);
157161
}
158162

159163
void PushHistory(const std::string& file_name, int32_t line) {

test/result_test.cc

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ TEST_F(ResultTest, smart_pointer_with_nullptr) {
384384
}
385385
}
386386

387-
TEST_F(ResultTest, NotOKThen) {
387+
TEST_F(ResultTest, NotOKThenAndAlwaysThen) {
388388
int flag = 0;
389389

390390
std::invoke([]() -> CustomResult {
@@ -418,6 +418,26 @@ TEST_F(ResultTest, NotOKThen) {
418418
});
419419

420420
EXPECT_EQ(flag, 3);
421+
422+
{
423+
int n_flag = 0;
424+
int a_flag = 0;
425+
426+
std::invoke([]() -> CustomResult {
427+
return CustomResult::Builder(CustomResult::ErrorCode::OtherError).Build();
428+
})
429+
.NotOKThen([&n_flag](auto&& res) {
430+
EXPECT_FALSE(res.IsOK());
431+
n_flag = 1;
432+
})
433+
.AlwaysThen([&a_flag](auto&& res) {
434+
EXPECT_FALSE(res.IsOK());
435+
a_flag = 1;
436+
});
437+
438+
EXPECT_EQ(n_flag, 1);
439+
EXPECT_EQ(a_flag, 1);
440+
}
421441
}
422442

423443
TEST_F(ResultTest, GetHistoryInfoNode) {

0 commit comments

Comments
 (0)