简体   繁体   中英

Symfony 2: How to catch Catchable Fatal Error?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM