refactored and solidied error handling