Magento – How to check if a product exists in Magento 2 without throwing \Magento\Framework\Exception\NoSuchEntityException

exceptionmagento2productrepository

I'm attempting to scan an incoming list of products and add any new ones to the catalog. Therefore, I must run a check on each product to see if it already exists.

I'm using a ProductRepositoryInterface via DI to load each product by SKU, but if the product doesn't exist within the catalog (new product), it fails with a \Magento\Framework\Exception\NoSuchEntityException.

How can I write logic around this so I can either: confirm the product exists, skip it gracefully, and move on OR confirm the product doesn't exist, and then add it? Is there something like an exists() method that I'm missing?

$product = $this->productRepository->get($xmlProductSku);

Best Answer

Same issue here Magento2 - ProductRepository always throws NoSuchEntityException

You'd use the concrete Exception class Magento are throwing in the try/catch block