Improved error handling and tests