open62541pp 0.15.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
exceptioncatcher.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <exception>
4#include <functional>
5#include <utility> // exchange, move
6
7namespace opcua::detail {
8
9/**
10 * Catch & store exceptions from user-defined callbacks in an exception-unaware context (open62541).
11 * The stored exception can be rethrown in a different context.
12 */
14public:
15 void setException(std::exception_ptr exception) noexcept {
16 exception_ = std::move(exception);
17 }
18
19 bool hasException() const noexcept {
20 return exception_ != nullptr;
21 }
22
23 void rethrow() {
24 if (hasException()) {
25 std::rethrow_exception(std::exchange(exception_, nullptr));
26 }
27 }
28
29 template <typename Callback, typename... Args>
30 void invoke(Callback&& callback, Args&&... args) noexcept {
31 static_assert(std::is_void_v<std::invoke_result_t<Callback, Args&&...>>);
32 try {
33 std::invoke(std::forward<Callback>(callback), std::forward<Args>(args)...);
34 } catch (...) {
35 setException(std::current_exception());
36 }
37 }
38
39 // template <typename OnException, typename Callback, typename... Args>
40 // auto invokeOr(OnException&& onException, Callback&& callback, Args&&... args) {
41 // static_assert(std::is_same_v<
42 // std::invoke_result_t<OnException, std::exception_ptr>,
43 // std::invoke_result_t<Callback, Args&&...>>);
44 // try {
45 // return std::invoke(std::forward<Callback>(callback), std::forward<Args>(args)...);
46 // } catch (...) {
47 // setException(std::current_exception());
48 // return std::invoke(std::forward<OnException>(onException), std::current_exception());
49 // }
50 // }
51
52 template <typename Callback>
53 auto wrapCallback(Callback&& callback) noexcept {
54 return [this, cb = std::forward<Callback>(callback)](auto&&... args) {
55 this->invoke(std::move(cb), std::forward<decltype(args)>(args)...);
56 };
57 }
58
59private:
60 std::exception_ptr exception_;
61};
62
63} // namespace opcua::detail
Catch & store exceptions from user-defined callbacks in an exception-unaware context (open62541).
void setException(std::exception_ptr exception) noexcept
auto wrapCallback(Callback &&callback) noexcept
void invoke(Callback &&callback, Args &&... args) noexcept
static UA_LogCategory const char va_list args