Fixed error handling and cleanup