Added more robust error handling