Improved error handling and debugging