Magento 2 Error Handling

🚨 Magento 2 Error Handling – Catch and Resolve Errors Like a Pro

Errors happen – but in Magento 2, we don’t run, we debug! 🧠 This tutorial shows how to handle, log, and resolve errors smartly in your Magento 2 development journey.

🧱 Try-Catch in Magento 2

To prevent your code from crashing the site, always wrap risky operations in try-catch blocks.

try {
    // Risky operation
    $product = $this->productRepository->getById($productId);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    $this->logger->error('Product not found: ' . $e->getMessage());
}

Try It Now

📝 Logging Errors

Use Magento’s built-in logging to write error messages to var/log/exception.log.

$this->logger->critical('Something went terribly wrong!');

Try It Now

🔍 Developer Mode for Detailed Errors

Switch to developer mode to see stack traces in the browser and get better debugging info:

php bin/magento deploy:mode:set developer

Try It Now

📄 Custom Error Pages

You can customize error pages in pub/errors. To enable detailed errors during development:

cp pub/errors/local.xml.sample pub/errors/local.xml

Try It Now

🐛 Display PHP Errors

Enable PHP error display in your index.php file temporarily:

ini_set('display_errors', 1);
error_reporting(E_ALL);

Try It Now

🚫 Suppress Exceptions Gracefully

In some cases, you may want to prevent exceptions from breaking functionality:

try {
    // Risky code
} catch (\Exception $e) {
    // Log it but don’t break the page
    $this->logger->warning('Non-critical error: ' . $e->getMessage());
}

Try It Now

📁 Magento Error Report Directory

Magento stores specific errors in var/report/. Each report is given a unique ID that shows on the error page.

To read the report, run:

cat var/report/1234567890

Try It Now

✅ Tips to Handle Errors Effectively

  • Use specific exceptions like NoSuchEntityException, LocalizedException, etc.
  • Don’t show raw errors in production – use logs!
  • Clean logs periodically: php bin/magento log:clean

That’s it! With proper error handling in place, your Magento 2 store stays solid and bug-free — and you stay stress-free. 😎