How to useTry Catch using in Magneto2.

Structure:-

try {
        /* Write  logic that could throw an Exception Error */
        
    } catch (\Exception $e) {
    
        /* Do to  Message */
    }
  • To start logging in our exceptions would be to inject the Psr\Log\LoggerInterface into constructor.
private $logger;

public function __construct(\Psr\Log\LoggerInterface $logger)
{
    $this->logger = $logger;
}
And then write catch statement.
public function WriteSomething()
{
    try {
        /* Some logic that could throw an Exception */

    } catch (\Exception $e) {

        $this->logger->critical($e->getMessage());
    }
}
Total Page Visits: 43108 - Today Page Visits: 13

Leave a Reply