Some error handling refactoring