refactoring error handling logic