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 Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

4 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

4 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

6 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago