Improved the logging and error handling