0
votes

How do I catch this type of error?

ContextErrorException: Catchable Fatal Error: Argument 1 passed to AA\SomeBundle\Entity\SomeEntity::setCity() must be an instance of AA\SomeBundle\Entity\City, null given, called in /srv/dev/some_path/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 360 and defined in /srv/dev/some_path/src/AA/SomeBundle/Entity/SomeEntity.php line 788

And I am trying to catch everything like that:

$form = $this->createForm(new SomeFormType(), $instanceOfSomeEntity);

try {
    $form->handleRequest($request);
} catch (\Exception $e) {
    $form->addError(new FormError('missing_information'));
}
2
Should you not be able to validate a form with a null field if the value can't be null? If your field can be null, just add setCity(City $city = null) in your SomeEntityAlixB
Your error is caused by leaving city field null. Use validation constraints to make sure that user set some valueBartek
Yep, thanks, I can see how to fix the entity, so it does not throw an exception. But still, is there a way to catch ContextErrorException?Georgij
A catchable fatal error is typically something that uses PHP's error reporting mechanism, not exceptions. It could be caught using a custom error handler.deceze♦

2 Answers

0
votes

The easiest way to fix this is to prefix the offending code with the @ symbol, so any warnings are suppressed. Any errors should then be caught in the try...catch.

Not ideal as @ has non-trivial performance implications, but otherwise, you're looking at perhaps replacing the error handling or in my case, when reading from XML, checking the existence of every tag before trying to get the value.

This is my code, fixed by adding the '@'

    try {
        $value = @$this->XML->StructuredXMLResume->ContactInfo->ContactMethod->PostalAddress->DeliveryAddress->AddressLine;
    } catch (\Exception $e) {
        $value = '';
    }

As you can imagine, checking every level down to AddressLine would be ridiculous.

-1
votes

You have to disable the error reporting and catch the last error with error_get_last() function, here an example, from the Symfony Finder component : https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Finder/SplFileInfo.php#L65

The other way is to create a custom error handler, here an example from Monolog : https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php