Add more error handling and tests for error cases