2

How can i get user by his email, or return null if not found? I need to do this in cron.

This code works

$CustomerModel = $objectManager->create('\Magento\Customer\Api\CustomerRepositoryInterface');

                        try {
                            $customerExists = $CustomerModel->get($email); //Here 1 means Store ID**
                        } catch (Exception $e) {
                            $customerExists = false;
                        }

But once I run it via cron, it returns an error that email is already in use, even when in try/catch block.

Any ideas?

1 Answer 1

2

You have done some mistake

You have changes

catch (Exception $e) {

to

catch (\Magento\Framework\Exception\NoSuchEntityException $e){
.....
}
catch (\Magento\Framework\Exception\LocalizedException $e){
...
}

NoSuchEntityException exception thrown by this class when if a customer with the specified email does not exist.

LocalizedException error thrown when other errors happen.

SEE Defination

/**
 * Retrieve customer.
 *
 * @param string $email
 * @param int|null $websiteId
 * @return \Magento\Customer\Api\Data\CustomerInterface
 * @throws \Magento\Framework\Exception\NoSuchEntityException If customer with the specified email does not exist.
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function get($email, $websiteId = null);
2
  • This seems to have fixed it, but why? Didnt "catch Exception $e" also catch NoSuchEntityException?
    – Bawsi
    Commented Aug 16, 2018 at 7:51
  • Magento2 use different type s of exception handling for API, so, it is introduce
    – Amit Bera
    Commented Aug 16, 2018 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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