better error handling in the main loop