3

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?

6

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);

}
1
  • I am not using _getSession , using _messageManager, can you update it according to that please. Aug 7 '18 at 16:00
0

Use following code to convert

use Magento\Framework\Exception\LocalizedException;

catch (LocalizedException $e) {

            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {

                $message = __('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);

            }
            else {
                $message = $e->getMessage();
            }
            $this->messageManager->addError($message);
        }
        catch (\Exception $e) {
            $this->messageManager->addException($e, __('Can\'t save user'));
        }
4
  • can we use this one? if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) { Aug 7 '18 at 7:51
  • @jafar no you need to convert every M1 code into M2 Aug 7 '18 at 7:52
  • Please i want that code. Aug 7 '18 at 8:18
  • @jafarpinjar did you get the code ? May 29 '19 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.