Refactored error handling and added tests