Error handling for the main loop