Magento2 – Custom Exceptions for Module

exceptionmagento2

There are a few good-answered questions like this for Magento 1, but I haven't found anything for Magento 2.

What should be the way for adding in custom module custom Exception class. Can I add some constant message renedered when custom exception is catched? I have foun 'heart' of exceptions in magento/framework/Exception, but I am not sure if this is place which I should extend from, because there can be found some exception classes in symfony vendor.

Are there any good practices for Magento 2 for custom Exceptions or do you think it is not worth adding our own exceptions and we should just customize message displayed or logged?

Best Answer

I can't guarantee that it's the best solution but when reading the source code of Magento 2 core files most modules do it this way:

  • Create a new folder called Exception in your module's directory.

  • Add a new PHP class (e.g. CustomResponseException) to this folder

  • The class CustomResponseException should extend the LocalizedException class. This class extends PHP's core Exception class

    This is how the file should look like:

    <?php
    
    namespace XYZCompany\CustomResponse\Exception;
    
    
    class CustomResponseException extends 
    \Magento\Framework\Exception\LocalizedException
    {
    }  
    
  • To throw this custom exception use the following statement within your catch block:

    throw new CustomResponseException('custommessage', $e);
    
Related Topic