1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#define CAF_SUITE custom_exception_handler
#include "caf/all.hpp"
#include "core-test.hpp"
using namespace caf;
#ifndef CAF_ENABLE_EXCEPTIONS
# error "building unit test for exception handlers in no-exceptions build"
#endif
behavior testee() {
return {
[](const std::string&) { throw std::runtime_error("whatever"); },
};
}
class exception_testee : public event_based_actor {
public:
exception_testee(actor_config& cfg) : event_based_actor(cfg) {
set_exception_handler([](std::exception_ptr&) -> error {
return exit_reason::remote_link_unreachable;
});
}
~exception_testee() override;
behavior make_behavior() override {
return testee();
}
};
exception_testee::~exception_testee() {
// avoid weak-vtables warning
}
CAF_TEST(the default exception handler includes the error message) {
using std::string;
actor_system_config cfg;
actor_system system{cfg};
scoped_actor self{system};
auto aut = self->spawn(testee);
self->request(aut, infinite, "hello world")
.receive( //
[] { CAF_FAIL("unexpected response"); },
[](const error& err) {
auto msg = err.context();
if (auto view = make_typed_message_view<string, string>(msg)) {
CHECK_EQ(get<1>(view), "whatever");
} else {
CAF_FAIL("unexpected error contest: " << err.context());
}
});
}
CAF_TEST(actors can override the default exception handler) {
actor_system_config cfg;
actor_system system{cfg};
auto handler = [](std::exception_ptr& eptr) -> error {
try {
std::rethrow_exception(eptr);
} catch (std::runtime_error&) {
return exit_reason::normal;
} catch (...) {
// "fall through"
}
return sec::runtime_error;
};
scoped_actor self{system};
auto testee1 = self->spawn<monitored>([=](event_based_actor* eb_self) {
eb_self->set_exception_handler(handler);
throw std::runtime_error("ping");
});
auto testee2 = self->spawn<monitored>([=](event_based_actor* eb_self) {
eb_self->set_exception_handler(handler);
throw std::logic_error("pong");
});
auto testee3 = self->spawn<exception_testee, monitored>();
self->send(testee3, "foo");
// receive all down messages
self->wait_for(testee1, testee2, testee3);
}
|