How to handle a Fatal Error

2

How to get a fatal error so that it does not terminate the application? This should be limited to only part of the code (this will not risk the application)?

Example: I would like all fatal error messages generated within this block not to terminate the application:

if($DocInfo->http_status_code === 200){
    //Print Page Title
    $html = str_get_html($DocInfo->content);
    $title = $html->find('title');
    echo $title[0]->plaintext.'<br />';
}
    
asked by anonymous 10.02.2015 / 17:30

1 answer

2

When you want to prevent mistakes from happening you have to ask yourself some things:

  • What kind of problem do you expect to happen? Is it possible to do a check before it happens? If you can, do it.
  • Is it possible to check if the error occurred afterwards without any major problems? Check before the result is used and generate another error.
  • If none of this is possible, what exceptions do you know that can happen in this section? Capture these specific exceptions.
  • Do not know what to capture? Capture them all. This should not be done but is the last alternative.

How to avoid error (based on what was said in the question comment):

if($DocInfo->http_status_code === 200){
    if ($DocInfo->content) {
        $html = str_get_html($DocInfo->content);
        $title = $html->find('title');
        echo $title[0]->plaintext.'<br />';
    } else {
        echo "deu erro aqui";
        //faz alguma coisa útil
    }
}

I would put more specific exception capture examples if I had access to the class documentation being used (and the documentation is well done, which is rare).

The last case would be:

try { 
    if($DocInfo->http_status_code === 200){
        //Print Page Title
        $html = str_get_html($DocInfo->content);
        $title = $html->find('title');
        echo $title[0]->plaintext.'<br />';
    }
} catch (Exception $ex) {
    echo "deu erro aqui";
    //faz alguma coisa útil
}

See more about capturing Exception .

In addition, you can set a function to capture all errors. It is also not recommended in most cases.

register_shutdown_function("nomeDaFuncao");

There you write what you want in the nomeDaFuncao function.

But there are reasons to avoid these non-recommended ways. Do not go the path that seems easier because it will become a complicator.

If you have a fatal error it is because you have a programming error. Then it must be corrected. It is not to pretend that the error does not exist. It may seem like it's not programming error but it's if you can avoid it. And it looks like it can be avoided.

    
10.02.2015 / 17:39