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?

1 Answer 1


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:

    namespace XYZCompany\CustomResponse\Exception;
    class CustomResponseException extends 
  • To throw this custom exception use the following statement within your catch block:

    throw new CustomResponseException('custommessage', $e);
  • So far I am using the same approach! Aug 1, 2017 at 12:38
  • Good to hear, I'm pretty confident that this is the solution how it should be done.
    – FaHu
    Aug 2, 2017 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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