Magento 2 Exception Handling – Best Practices

exceptionmagento2

I have created a custom controller to create customer using try catch,

below is my magento1 code of controller

How this can be used in magento2?

  try {
      $user = Mage::getModel('customer/customer')->setId(null);
      $data = $this->getRequest()->getPost();


        $defaultFields = array();
        foreach (Mage::getConfig()->getFieldset('customer_account') as $code=>$node) {
            $defaultFields[] = $code;
            if ($node->is('create') && isset($data[$code])) {
                if ($code == 'email') {
                    $data[$code] = trim($data[$code]);
                }
                $user->setData($code, $data[$code]);
            }
        }
      $user->save();
  }
  catch (Mage_Core_Exception $e) {
            $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
                $url = Mage::getUrl('customer/account/forgotpassword');
                $message = $this->__('There is already an account with this emails address. If you are sure that it is your email address, <a href="%s">click here</a> to get the password and access your account.', $url);
                $this->_getSession()->setEscapeMessages(false);
            }
            else {
                $message = $e->getMessage();
            }
            $this->_getSession()->addError($message);
        }
        catch (Exception $e) {
            $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
                ->addException($e, $this->__('Can\'t save user'));
        } 

Below code i used on m2

class CreatePost extends \Magento\Framework\App\Action\Action
{
protected $_customerSession; 
protected $customerFactory;
protected $_objectManager;
protected $_messageManager;
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Customer\Model\Session $customerSession, 
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    \Magento\Framework\ObjectManagerInterface $objectmanager,
    \Magento\Framework\Message\ManagerInterface $messageManager,
) {
    $this->_fieldsetConfig = $fieldsetConfig;
    $this->_customerSession = $customerSession; 
    $this->customerFactory  = $customerFactory;
    $this->_objectManager = $objectmanager; 
    $this->_messageManager = $messageManager;   
    parent::__construct($context);
}  
  if ($this->getRequest()->isPost()) {
  $data = $this->getRequest()->getPost();
        $defaultFields = array();
        $customerAccount = $this->_fieldsetConfig->getFieldset('customer_account');         
        foreach ($customerAccount as $code=>$node) {
            $defaultFields[] = $code;
            if ((isset($node['create'])) && (isset($data[$code]))) {
                if ($code == 'email') {
                    $data[$code] = trim($data[$code]);
                }
                $user->setData($code, $data[$code]);

            }
        }
try {
            $user->save();  
            $this->_messageManager->addSuccess(__('User was successfully created.'));           
            return $this->_redirect('*/*/listuser/');

        }catch (\Exception $e){
           $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e->getMessage());
           $this->_messageManager->addError(__('We were unable to submit your request. Please try again!'));
           return $this->_redirect('*/*/listuser/');
        }
 }

Please anyone help me on this how try catch is used for above code in magento2 format?

Best Answer

Magento throw, \Magento\Framework\Exception\AlreadyExistsException error type when we have we have tried to a new account on an existing email address.

$result = $connection->fetchOne($select, $bind);
        if ($result) {
            throw new AlreadyExistsException(
                __('A customer with the same email already exists in an associated website.')
            );
        }

So, on Controller, you can handler by this type of code

try{
......
}catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
    $message = $this->__('There is already an account with this emails address. If you are sure that it is your email address, <a href="%s">click here</a> to get the password and access your account.', $url);
    $this->_getSession()->addError($message);
}catch(\Magento\Framework\Exception\LocalizedException $e){
 $message = $e->getMessage();
 $this->_getSession()->addError($message);
}catch (\Exception $e) {
    $message = $e->getMessage();
    $this->_getSession()->addError($message);
}

BEIEF:

Magento2 have used little bit different type of exception handling for creating thrown exception and check the exception type.

Before the understand how to define the exception and what type of exception, Magento use then you have to check Magento in -build exception type

Here the list exception type from Magento/Framework/Exception

AbstractAggregateException
AlreadyExistsException
AuthenticationException
AuthorizationException
ConfigurationMismatchException
CouldNotDeleteException
CouldNotSaveException
CronException
EmailNotConfirmedException
FileSystemException
InputException
IntegrationException
InvalidEmailOrPasswordException
LocalizedException
MailException
NoSuchEntityException
NotFoundException
PaymentException
RemoteServiceUnavailableException
RuntimeException
SecurityViolationException
SerializationException
SessionException
StateException
TemporaryStateExceptionInterface
ValidatorException

This exceptions type are used at Magento2.

How Magento define the exception.

Define Error type

Suppose, you want show throw exception of already to exist then

Then you throw error like

 if (Condition) {
        throw new \Magento\Framework\Exception\AlreadyExistsException(
            __('This record already exits')
        );
    }

Check catch error Type

Check the error type and catch section using below pattern:

  catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
    $this->messageManager->addError($message);
}

For your case you can use below catch handling logic

catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
    $message = $this->__('There is already an account with this emails address. If you are sure that it is your email address, <a href="%s">click here</a> to get the password and access your account.', $url);
 $this->_getSession()->addError($message);
}catch(\Magento\Framework\Exception\LocalizedException $e){
$message = $e->getMessage();
 $this->_getSession()->addError($message);
}catch (\Exception $e) {
            $message = $e->getMessage();
 $this->_getSession()->addError($message);

}