Saturday, September 10, 2011

A SIMPLE SOLUTION TO HANDLING PHP FATAL ERRORS

Hey, I'm also a web developer and I encountered a problem while developing a php application - PHP can't handle fatal errors! It just exits after encountering one. Tsk tsk tsk.

Well everybody says that you can't catch php fatal errors.
I have a solution. It utilizes the grep command (for linux and unix users) to check lines that say "PHP".
Though it's does not follow best programming pratices, it still does the job.

First task is to create a separate php script that contains the lines of code you want to catch.

For example:

<?php
non_existent_function_foo_bar();
?>

as test.php

Now write another script to run the first script using exec or the ` ` delimiters.

<?php
$a = exec("php test.php | grep php");
echo $a;
echo "\nMy my it recovered! Excellent solution, dann!";
?>

See what happens:
Well this does not handle variables that you want to pass on to the next script. However, that's trivial. You can pass it as a commandline argument. If you want it more difficult, write to an xml file, or a plain text all the variable values you want to pass then just read them from the next script.

Now you can use this principle to generate an Exception when such errors are encountered or to recover from a fatal error!

Sometimes the most practical solution may not be the most beautiful solution.

Haha!

No comments:

Post a Comment