Improved error catching