Fix error handling and test cases