1

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?

9

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.