Added better handling for exceptions and logging