Improving error handling and logging