refactor error handling