Improved error handling and test