How To

How to Throw an Exception from Event Observer in Magento2

In this Ecommerce era, when everyone is looking for all in one ultimate platform that fulfils all your business needs, Magento is topping a list with its functionality, features & security enhancements that it offers for their users. Not just by features, but you can also integrate third-party extensions one can customize Magento core functionality according to your needs. But, we always suggest you to do not modify core functionality instead you can override code functionality or you can make use of Magento Extensions to make things easy. But have you ever wonder, how it works in the background?
Any Magento 2 Extensions, you have used till date is made up so many of lines of codes that contain different events and observers. Event is nothing but one kind of action that triggers when a specific action is performed and the Observer is designed to catch those actions. When any action is triggered, it will pass data to the relevant observer that is configured for the dispatched event. There are so many Magento events like perform an action after the product adds to cart, after or before customer account create etc. Whenever any of these events is triggered, it is important to display a relevant message in-store frontend to notify the user as there are thousands of events are builtin. So, today we are again back with another blog that will help you to display an event-related message.
Here, we have implemented the observer called “sales_quote_remove_item” and for that, we want to show an error message if the customer tries to remove any product.
First, we need to declare our Event observer by creating “events.xml” file at this path in our extension folder.
app\code\Vendor\Extension\etc\frontend\

<pre class="lang:default decode:true">
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="sales_quote_remove_item">
    <observer name="sales_quote_remove_item_handler" instance=" Vendor\Extension \Observer\RemovecartbeforeObserver" shared="false" />
  </event>
</config>
</pre>

After that, we need to create the “RemovecartbeforeObserver.php” in our extension observer folder.
app\code\Vendor\Extension\Observer\

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
class RemovecartbeforeObserver implements ObserverInterface
{
   protected $messageManager;
   protected $resultRedirectFactory;
    public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Framework\Controller\Result\RedirectFactory
 $resultRedirectFactory)
   {
       $this->messageManager = $messageManager;
       $this->resultRedirectFactory = $ resultRedirectFactory;
   }
   public function execute (\Magento\Framework\Event\Observer $observer)
   {
       // HERE IS MY CODE
       $message = "THIS IS CUSTOM ERROR MESSAGE";
       $this->messageManager->addError($message);
        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }
 }
</pre>

Tadaa! You have successfully thrown an error exception if your customer tries to remove any product from their shopping cart.

You are free to customize this code according to your displaying message for multiple events or observers.

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issue while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 14 Average: 4]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

  • Can I validate a product before it is saved in Magento 2 basically I want to show an error message when the product is saved if the product does not contain the necessary data?

Recent Posts

How to Add a Custom Field to the Cart Price Rules Form in Magento 2?

Hello Magento Friends, In this blog, we will learn How to Add a Custom Field…

7 hours ago

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

1 week ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago