Maintainability 101

Maintainability — Handling exceptions.

Let’s see together why it’s important and how it can change the way you code.

try {
$remover->remove($group);
} catch (\Exception $exception) {
return new JsonResponse(['message' => $exception->getMessage()], 500);
};
try {
$remover->remove($group);
} catch (MyGroupUserException $exception) {
// We know this exception is safe to be sent to the user.
return new JsonResponse(['message' => $exception->getMessage()], 500);
} catch (MyGroupException $exception) {
// This exception is not safe and should not happen. So we log and send a generic exception.
$this->logger->error("There was an error while deleting the user group : {$exception->getMessage()}", ['exception' => $exception]);
return new JsonResponse(['message' => "The grouop coudln't be deleted"], 500);
};
// All other exceptions will be handle by the framework.
try {
$remover->remove($group);
} catch (\Exception $exception) {
$this->logger->error("There was an error while deleting the user group : {$exception->getMessage()}", ['exception' => $exception]);
return new JsonResponse(['message' => "The group couldn't be deleted"], 500);
};

Logging

To wrap it up.

Another example

try {
$page = $this->resultPageFactory->create();
$this->viewHelper->prepareAndRender($page, $productId, $this, $params);
return $page;
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
return $this->noProductRedirect();
} catch (\Exception $e) {
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
$resultForward = $this->resultForwardFactory->create();
$resultForward->forward('noroute');
return $resultForward;
}

Conclusion

Passionate web developer. Symfony lover. Writing as a hobby. Sad Magento 2 developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store