Magento 2 Product – How to Catch Exception if SKU Does Not Exist in ProductRepository

exceptionmagento2product

I am writing a console command to update catalog stock, but I am facing some weird issue when trying to load products by sku. I am using this code…

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepo = $objectManager->create('Magento\Catalog\Model\ProductRepository');

And then, after getting $sku from a csv read function…

try {
    $product = $productRepo->get($sku);
} catch (Exception $e){
    $product = false;
}
echo "1"; exit;

I have placed that echo "1"; just to check but that "1" is never reached… result is always [Magento\Framework\Exception\NoSuchEntityException] Requested product doesn't exist

So, how can I catch that Exception?

Best Answer

I thought I could catch that using generic php Exception class, but it seems we need to use the concrete throwed Exception

Using this code, then the try/catch block works

try {
    $product = $productRepository->get($sku);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e){
    $product = false;
}