Throwing exception based on condition in before plugin
-
14-03-2021 - |
Frage
I'm creating a before plugin
for the class \Magento\Customer\Controller\Account\EditPost
. In the execute
method I want to throw an Exception based on certain condition but the plugin is showing output like this.
I want to print proper exception message in notification area like this.
Here is my Plugin Class
class EditPost {
public function beforeExecute(\Magento\Customer\Controller\Account\EditPost $subject) {
throw new \Exception('Exception trigger');
return $subject;
}
}
What I'm doing wrong here.
Lösung
This is my solution using around plugin
.
public function aroundExecute(\Magento\Customer\Controller\Account\EditPost $subject, $proceed) {
if(true) { // for true condition
$this->messageManager->addErrorMessage('My custome Error');
/** @var Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/edit');
return $resultRedirect;
}
return $proceed();
}
Andere Tipps
You can still use your before plugin and use \Magento\Framework\Message\ManagerInterface
for this.
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
private $messageManager;
public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager)
{
$this->messageManager = $messageManager;
}
public function beforeExecute(\Magento\Customer\Controller\Account\EditPost $subject) {
try {
//your code
throw new \Exception('Exception trigger');
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return null;
}
The important part is if you decide to throw an exception that you catch it. Then you can use the Message\Manager
to display your desired message.
If you return null
or as in your answer with the around plugin $proceed()
keep in mind that the base method will be executed and it will still save the customer.