Improved error handling and logging