Question

I'd like to plug an after plugin to the admin controller saving attribute data (Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save) but this plugin should be processed only if no error/exception occurred during controller execution. Question is: how can I found this out since there's no public method for accessing redirection url with \Magento\Framework\Controller\Result\Redirect\Redirect\Redirect class ?

I thought this would be rather a common case with after plugin but I found no similar question across the web.

Was it helpful?

Solution

If the method you are using throws an exception. The afterPlugin will not be executed.

You can try using this code.

class ValidateSomething
{
    public function afterBeforeSave(Product $product): Product
    {
        die('i am coming');
        return $product;
    }
}

in etc\adminhtml\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\Catalog\Model\Product">
        <plugin name="somename"
                type="Company\Module\Plugin\ValidateSomething"/>
    </type>

</config>

in \Magento\Catalog\Model\Product.php throw an exception

    public function beforeSave()
    {
        throw new \Exception('something went wrong');
    }

You will now see that whenever you try to save a product in magento admin. Error will be shown "something went wrong" but the afterBeforeSave in class ValidateSomething wont be executed.

Once you remove that exception in \Magento\Catalog\Model\Product.php and test the code. The code "i am coming" from class ValidateSomething will be executed.

Magento custom development http://rosenborgsolutions.com/how-to-extend-magento-part-1.php

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top