When you want to prevent mistakes from happening you have to ask yourself a few 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 after without major problems? Check before the result is used and generate another error.
- If none of this is possible, what exceptions do you know can happen in this excerpt? Capture these specific exceptions.
- Don’t know what to capture? Capture them all. This shouldn’t 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 often 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
}
I put in the Github for future reference.
See more about capturing Exception
.
In addition it is possible to rewrite a function to capture all errors. It is also not recommended in most cases.
register_shutdown_function("nomeDaFuncao");
Then you write whatever you want in the function nomeDaFuncao
.
But there are reasons to avoid these recommended ways. Don’t go the way 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 fixed. It is not to pretend that the error does not exist. It may seem that it is not programming error but it is if you can avoid it. And it seems that it can be avoided.
Sorry, excuse me, don’t close the app
– Ricardo
What is the fatal error you receive? Sometimes it is better to avoid the error than try to recover from it.
– André Ribeiro
@Andréribeiro, there is no way to avoid the fatal error, it is generated when $Docinfo->content is false, (it is false because of network error among other peculiar reasons) to circumvent the fatal error in this part of the code would not influence the correct functioning of the application
– Ricardo
@Richerdohenrique and the problem is that it gets fake, just check first and don’t use it. I won’t say there’s nothing that can be avoided, of course there is, but it doesn’t seem to be this case.
– Maniero