Added error handling and improved tests