Magento – show error message through plugin Magento2 in checkout page

errormagento2pluginshipmentzipcode

I am using a plugin feature in module to validate the zip code for delivery available. I need to prevent the next step if the zip code is not available for delivery by showing a message in checkout page. hear i have get error message in console but not showing in site

Hear is my code

/app/code/Ship/Details/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Model\ShippingInformationManagement">
        <plugin name="get_shipping_info" type="Sem\Shipment\Plugin\Checkout\Model\ShippingInformationManagement" sortOrder="1" disabled="false"/>
    </type>
</config>

plugin code

/app/code/Sem/Shipment/Plugin/Checkout/Model/ShippingInformationManagement.php

<?php

namespace Sem\Shipment\Plugin\Checkout\Model;
use Magento\Framework\Exception\StateException;

class ShippingInformationManagement
{

    protected $_messageManager;
    protected $jsonResultFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->_messageManager = $messageManager;
        $this->jsonResultFactory = $jsonResultFactory;
    }

    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation

    )
    {
    $address = $addressInformation->getShippingAddress();
    $postcode = $address->getData('postcode');
    $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
    $result = $this->jsonResultFactory->create();
    $stat="no sevice";
    throw new StateException(__($stat));             
}
}

In my console
enter image description here

How can i resolve this issue now the message is not showing also i cant move to next step payment

Best Answer

Please use like this:

public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->_messageManager = $messageManager;
        $this->jsonResultFactory = $jsonResultFactory;
        parent::__construct($context);
    }
Related Topic