refactored and added error handling for the most common scenarios