Refactoring the code and error handling