Better error handling and cleanup