Skip to main content
2 of 4
added 680 characters in body
Amit Bera
  • 77.7k
  • 20
  • 124
  • 239

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

Before thrown the exception and check you have to check Magento in build excpetion type

Here the list exception type from Magento/Framework/Exception

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

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

catch error So, on your try and catch section

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

}
Amit Bera
  • 77.7k
  • 20
  • 124
  • 239