cancel
Showing results for 
Search instead for 
Did you mean: 

Exception from controller to view

SOLVED
   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

Exception from controller to view

in my controller, I have this code (I'm getting last order through a form):

    ...
      

foreach($array as $item){
try {
$product = $this->_productRepository->getById($item['product_id']);
$product_id = $product->getId();

} catch (NoSuchEntityException $e) {
$this->messageManager->addErrorMessage('Un ou plusieurs produits n\'existe(nt) plus');
continue;
}

if(isset($product)){
$param = array(
'product' => $item['product_id'],
'qty' => $item['qty']
);
}
}


I want to display a simple message on my view. The exception is way to big, I want only to show 'product doesn't exist'. How can I do that ? I saw that I can achieve this with "message manager", but how can I get the exception from the controller to my view ?

 

On the front, I try

$e->getMessage()

but $e is not define

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Exception from controller to view

In fact, this is working. I didn't need to show $e, it's automatically ^^,

View solution in original post

2 REPLIES 2

Re: Exception from controller to view

In fact, this is working. I didn't need to show $e, it's automatically ^^,

Re: Exception from controller to view

You can use throw for send message to front,

foreach($array as $item){
    try {
        $product = $this->_productRepository->getById($item['product_id']);
        $product_id = $product->getId();

    } catch (NoSuchEntityException $e) {
        throw new \Magento\Framework\Exception\LocalizedException(__('Un ou plusieurs produits n\'existe(nt) plus'));
        continue;
    }

    if(isset($product)){
        $param = array(
            'product' => $item['product_id'],
            'qty' => $item['qty']
        );
    }
}
If Issue Solved, Click Kudos/Accept As solutions. Get Magento insight from
Magento 2 Blogs/Tutorial