Improve error handling and logging