Improve logging and error handling