Added error capturing and logging.