Improved the error handling and loggin