slightly more robust error handling

This commit is contained in:
Lily Tsuru 2024-02-02 20:26:27 -05:00
parent 8196f711bc
commit ee1ef5906d
3 changed files with 71 additions and 55 deletions

View File

@ -8,13 +8,16 @@ namespace nanosm {
epollFd = epoll_create1(EPOLL_CLOEXEC);
if(epollFd == -1) {
perror("You Banned From Epoll, Rules");
throw std::system_error(std::make_error_code(static_cast<std::errc>(errno)));
return;
}
}
EventLoop::~EventLoop() {
if(epollFd == -1) {
close(epollFd);
}
}
void EventLoop::Post(PostFn func) {
if(!func)
@ -56,15 +59,15 @@ namespace nanosm {
UniqueArray<epoll_event> events { 16 };
while(!shouldStop) {
auto nevents = epoll_wait(epollFd, events.Get(), events.Size(), 10);
if(nevents == -1) {
perror("epoll_wait");
break;
// The timeout here is larger than it probably would be if e.g: this was dealing with sockets,
// mostly because nanosm is designed to only really use CPU if it has to (i.e: a process died, timer elapsed, etc)
auto nrEvents = epoll_wait(epollFd, events.Get(), events.Size(), 50);
if(nrEvents == -1) {
throw std::system_error(std::make_error_code(static_cast<std::errc>(errno)));
}
// All OK, let's check for events now
for(int i = 0; i < nevents; ++i) {
if(nrEvents != 0) {
for(int i = 0; i < nrEvents; ++i) {
for(auto pollable : ioObjects) {
if(auto fd = pollable->GetFD(); fd != -1) {
// Signal any events that occur for this
@ -73,8 +76,10 @@ namespace nanosm {
}
}
}
}
// Run the topmost callback once every event loop iteration.
// Run the topmost callback once every event loop iteration,
// even if epoll never signaled readiness.
if(!postCallbacks.empty()) {
auto& frontCallback = postCallbacks.front();
frontCallback();

View File

@ -7,8 +7,9 @@ namespace nanosm {
Timer::Timer(nanosm::EventLoop& ev)
: nanosm::EventLoop::IoObject(ev) {
timerFd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if(timerFd < 0)
perror("timerfd_create");
if(timerFd < 0) {
throw std::system_error(std::make_error_code(static_cast<std::errc>(errno)));
}
}
Timer::~Timer() {

View File

@ -2,6 +2,7 @@
#include <format>
#include <map>
#include <memory>
#include <system_error>
#include <toml++/toml.hpp>
#include "EventLoop.hpp"
@ -82,7 +83,12 @@ struct NanoSm {
this->SpawnAllApps();
});
try {
ev.Run();
} catch(std::exception& ec) {
nanosm::log::Error("NanoSm", "Unhandled exception in event loop: {}", ec.what());
return 1;
}
return 0;
}
@ -105,6 +111,7 @@ fs::path GetConfigPath() {
}
int main(int argc, char** argv) {
try {
NanoSm nanosm;
auto configPath = GetConfigPath();
@ -146,10 +153,13 @@ int main(int argc, char** argv) {
return 1;
}
return nanosm.Run();
} catch(toml::parse_error& pe) {
std::fprintf(stderr, "Error parsing config file \"%s\": %s\n", configPath.c_str(), pe.description().data());
return 1;
}
return nanosm.Run();
} catch(std::exception& ec) {
nanosm::log::Error("NanoSm", "Error initalizing NanoSm: {}", ec.what());
return 1;
}
}