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?