TartanLlama / expected

C++11/14/17 std::expected with functional-style extensions
https://tl.tartanllama.xyz
Creative Commons Zero v1.0 Universal
1.54k stars 133 forks source link

Add `error_or` to round off functional interface #118

Open operator-name opened 2 years ago

operator-name commented 2 years ago

error_or would be the compliment to value_or

The motivation here is to flesh out the error handling path. When an error occurs it's likely that other expected functions may be called to cleanup. At the moment this would look like this:

auto delete_file = [](auto&& err){
    return do_delete()
       .and_then([err = srd::move(err ](auto&& _) { return tl::make_unexpected(err); }) // propogage initial error
       .error()
};

create_file()
   .and_then(write_file)
   .map_error(delete_file)
   .and_then(rename_file)

With error_or, delete_file could look like:

auto delete_file = [](auto&& err) {
    return do_delete()
       .error_or(err);
};

on_error is a more powerful or_else, it could conditionally turn an error into a value again. This would also be useful during error handling, perhaps as a "cleanup and try a different technique that might still fail" type function.

This is also suggested in the proposal: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2505r4.html