Improve error handling and tests