Magento 2 : Event Observer Exception Not Showing in Screen
I search some more things on this and finaly found my solution,
I need to just change the observer code like this.
app\code\Vendor\Extension\Observer\RemovecartbeforeObserver.php
use Magento\Framework\Event\ObserverInterface;
class RemovecartbeforeObserver implements ObserverInterface
{
protected $messageManager;
protected $_responseFactory;
protected $_url;
public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url)
{
$this->messageManager = $messageManager;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
// HERE IS MY CODE
$message = "THIS IS CUSTOM ERROR MESSAGE";
$this->messageManager->addError($message);
$cartUrl = $this->_url->getUrl('checkout/cart/index');
$this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse();
exit;
}
}
Update your class to be like this:
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Message\ManagerInterface as MessageManagerInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
class RemovecartbeforeObserver implements ObserverInterface
{
protected $messageManager;
protected $redirectFactory;
public function __construct(
MessageManagerInterface $messageManager,
RedirectFactory $redirectFactory
) {
$this->messageManager = $messageManager;
$this->redirectFactory = $redirectFactory;
}
public function execute(Observer $observer)
{
$observer->getRequest()->setParam('item', false);
$message = "THIS IS CUSTOM ERROR MESSAGE";
$this->messageManager->addError($message);
return $this->redirectFactory->create()->setPath('*/*/');
}
}