1

I have following code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customer = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface')->getById($order->getCustomerId());
$mitgliedsnummer = $customer->getCustomAttribute('mitgliedsnummer');

When a customer has been deleted and this code gets executed it throws

NoSuchEntityException

However I want the code to continue. What can I do?

Thanks!

Update:

After applying simonthesorcerers suggestion it still happens.

    try {
        $customer = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface')->getById($order->getCustomerId());
    } catch(NoSuchEntityException $e) {
        $customer = null;
    }
    error_log("Test");

Update 2: include

use \Magento\Framework\Exception\NoSuchEntityException; to your namespace.

Thanks to simonthesorcerer!

1

For the question, you should simply use a try...catch construct. This is an example:

try {
    $mitgliedsnummer = $customer->getCustomAttribute('mitgliedsnummer');
} catch(\Magento\Framework\Exception\NoSuchEntityException $e) {
    // do something with $e, for example log $e->getMessage()
}
// code will continue to run here

More can be found in the official docs: http://php.net/manual/de/language.exceptions.php

However, remember that $mitgliedsnummer will have no value afterwards, so your program should be able to deal with that and may simple return $this; in the catch() {} segment.

You should also use dependency injection in your class's __construct() method instead of the ObjectManager, see the official docs here: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html

  • It still prints an error site then – k33n Apr 12 '18 at 11:51
  • is it the same error? do you have use \Magento\Framework\Exception\NoSuchEntityException; after your namespacedeclaration? ; edited my answer and added full path – simonthesorcerer Apr 12 '18 at 11: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.