Exception handling in Magento 2

The easiest way to start logging your exceptions would be to inject the Psr\Log\LoggerInterface into your class's constructor:

private $logger;

public function __construct(\Psr\Log\LoggerInterface $logger)
{
    $this->logger = $logger;
}

And then in your catch statement:

public function doSomething()
{
    try {
        /* Some logic that could throw an Exception */
    } catch (\Exception $e) {
        $this->logger->critical($e->getMessage());
    }
}

Anything else related to how to react after an exception has been caught shouldn't be any different between M1 and M2. Your strategy would also be very specific to your exception handling use case.


Magento2 has different types of Exception handlers, for example:

  • StateException
  • InputException
  • InvalidEmailOrPasswordException
  • MailException
  • NotFoundException
  • ValidatorException

Etc.

All handler types and their classes exist in \vendor\magento\framework\Exception.

You need to choose the relevant Exception handler for your requirements and use that.