In my plugin i have added an call to an remote api call. And if there is an error the customer needs to be redirected back to the cart and show the error.
I have this code but it doesnt work as expected.
try { $this->_stock->reserveRemoteStock(); } catch (\Magento\Framework\Exception\LocalizedException $e) { if ($this->_session->getUseNotice(true)) { $this->_messageManager->addNotice($e->getMessage()); } else { $messages = array_unique(explode("\n", $e->getMessage())); foreach ($messages as $message) { $this->_messageManager->addError($message); } } $url = $this->_session->getRedirectUrl(true); if ($url) { return $this->resultRedirectFactory->create()->setUrl($url); } else { $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl(); return $this->resultRedirectFactory->create()->setUrl($this->_redirect->getRedirectUrl($cartUrl)); } } catch (\Exception $exc) { throw new LocalizedException(__($exc->getMessage())); }
Thank you for your help.
Instead return... throw an exception like:
throw new \Magento\Framework\Exception\CouldNotSaveException( __('Please agree to all the terms and conditions before placing the order.') );
Also, I saw that in your lines like:
return $this->resultRedirectFactory...
...are missing ->sendResponse(); at the end of line.
Thank you for your answer, when I throw an exception I dont get redirected, I stay at the last step of the checkout (payment). The ->sendResponse(); was the trick of redirecting. But now all error messages are not displayed.
I Thought I could use the \Magento\Framework\Message\ManagerInterface for that. Or I'm doing something wrong there.