Magento 2 Product ID by SKU Error – Handling Non-Existent Product Error

magento2magento2.1.6

I am writing a module that takes a users input of product SKU (via a form) and then adds to the cart.

The issue I'm having is that when I am testing by using a non existent SKU the exception that is thrown can not be caught and leads to an exception on page.

Ideally I want to be able to catch the exception and display as a nice message to the user.

In my controller I am getting the product like so:

<?php
public function __construct(Context $context,
                            \Magento\Framework\View\Result\PageFactory $resultPageFactory,
                            \Magento\Checkout\Model\Cart $cart,
                            \Magento\Catalog\Model\ProductRepository $productRepository)
{
    $this->_resultPageFactory = $resultPageFactory;
    $this->_cart = $cart;
    $this->_productRepository = $productRepository;
    parent::__construct($context);
}

public function execute()
{
    $postParams = $this->getRequest()->getParams();
    // ... extract SKU process removed for clarity.

        //////// HERE IS THE ISSUE ////////////////
        try{
            $p = $this->_productRepository->get($sku);
        }catch(Exception $e){
            // this isn't caught, but outputed to the browser
            $errMsg = 'error: '.$e->getMessage();
        }
}
?>

Is there another way I can determine if a product SKU exists?

Thanks

Best Answer

Instead of using the ProductRepository , inject the ProductFactory:

 public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
        {
            $this->productFactory = $productFactory;
        }

and load like this:

$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
Related Topic