Refactored code with error handlers
Formatted some code blocks