Refactored error catching