0

Here I Want to show exception message like "Request Parameter is not found". Here is my code.

use Magento\Framework\Exception\StateException;

 protected $order;

public function __construct(
    \Magento\Sales\Api\Data\OrderInterface $order
) {
    $this->order = $order;
  }

public function getorderaddresslist($orderid) {
    try {
    $order = $this->order->load($orderid);
    $shippingAddress = $order->getShippingAddress()->getData();
    $billingAddress = $order->getBillingAddress()->getData();
    $address = array(
            'addresses' => [
            'shippingAddress' => $shippingAddress,
            'billingAddress' => $billingAddress
            ]
        );

      json_encode($address); 
     }
    catch(\Exception $e){
       throw new StateException(__('Request Parameter is not matched.'));
    }

How i can show a message if request parameter is not matched.can any help me.

2

You can use message manger to show error message whenever exception will come.

use Magento\Framework\Exception\StateException;

protected $order;

public function __construct(

    \Magento\Sales\Api\Data\OrderInterface $order,
    \Magento\Framework\Message\ManagerInterface $messageManager

) {

    $this->order = $order;
    $this->messageManager = $messageManager;

  }

public function getorderaddresslist($orderid) {

    try {

    $order = $this->order->load($orderid);

    $shippingAddress = $order->getShippingAddress()->getData();

    $billingAddress = $order->getBillingAddress()->getData();

    $address = array(
            'addresses' => [
            'shippingAddress' => $shippingAddress,
            'billingAddress' => $billingAddress
            ]
        );


      json_encode($address); 

     }

    catch(\Exception $e){

       $this->messageManager->addErrorMessage(__('Request Parameter is not matched.'));

    }
0

You can use message manager in the catch block to show the message as shown below;

class Example
{
    protected $_messageManager;

    public function __construct(
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->_messageManager = $messageManager;
    }

    public function method( ) {
        ..
        try{
            ....
         }
       catch(\Exception $e){
        $message = '...';
        $this->_messageManager->addError($message);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.