refactored the error handling