fix and add tests for error handling