Magento Best Practices – Try/Catch in Templates

best practicemagento2templatetemplate-directive

I have a question about best practices in templates.

Let's assume I am editing the product details template file. I would like to call a method in the product model which can raise an exception.

What is the best way to proceed :

  • to put the call in a verbose try / catch in the template, displaying the appropriate result in case of success/failure ;
try {
    echo $product->getSomething()->getName();
} catch (NoSuchEntityException $ex) {
    echo "No related Something";
} catch (\Exception $ex)) {
    echo "An error occured while extracting the related Something";
}
  • or creating an intermediate method (in the block ?), handling the try catch and returning and array with the result (if success) and a possible message, to make the template cleaner?
$result = $block->getSomething();
if($result['message'] === "") { // Everything went well
    echo $result['Something']->getName();
} else { // Something went wrong
    echo $result['message'];
}

Best Answer

In my opinion templates don't have to contain any logic on that point.
If we take your exemple, the best way is to make the try / catch in the block, the template is here only to display data.

Block file

<?php

class Foo extends \Magento\Framework\View\Element\Template
{
    [...]
    public function getName()
    {
        [...]
        try {
            return $product->getSomething()->getName();
        } catch (NoSuchEntityException $ex) {
            $this->logger->critical($ex);

            return false;
        } catch (\Exception $ex)) {
            $this->logger->critical($ex);

            return false;
        }
    }
}

Template file

<?php
/** @var string|false $name */
$name = $block->getName();
?>

[...]
<?php if ($name): ?>
   // logic...
<?php endif; ?>

In your case you can imagine different types of return in your block function and test them on your template to display the right information.

Related Topic