Error Handling

Ive been trying to handle errors correctly in PHP, and although I seem to be able to control some error in my code I cant seem to handle myself, such as missing ; from the of the line.

Is there anyway I can handle all errors, warnings and notices?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
There has never been a good solution to "all things error" in any programming language, and PHP is particularly bad at it.  Just an aside, PHP requires the semi-colon to end a statement, which can span several lines of text.  JavaScript does not require the semi-colon and, under certain conditions, JavaScript assumes that you meant to put a semi-colon into your text.  This has been the cause of more JavaScript errors than can be counted.

If you want to have a lot of "fun" with error handling learn about Exceptions, which can be used to cause space-time-travel in your programming.  Exception chains, like multiple inheritance, are just too complicated to be a good idea, even if the computer scientists want to tell us otherwise.  Simplicity and clarity of thought are virtues in software development.  CRC cards are worth more than all the error handlers in the world.

Here are the settings I use for deployed applications:
ini_set('display_errors', FALSE);
ini_set('log_errors', TRUE);
ini_set('error_log', 'error_log');

Open in new window

Here are the settings I use for development and test:
ini_set('display_errors', TRUE);
ini_set('log_errors', TRUE);
ini_set('error_log', 'error_log');

Open in new window

These settings can be set in php.ini or .user.ini and other places, depending on your server and PHP installations.

Here is a script that will traverse the directory tree and find all instances of 'error_log' allowing you to see and optionally delete the files.
<?php // demo/find_error_log.php

$path = realpath(getcwd());
$plen = strlen($path);

$signal = strrev(ini_get('error_log'));

if (!empty($_POST['log']))
    $test = strrev($_POST['log']);
    if (strpos($test, $signal) === 0)
        unlink($path . $_POST['log']);
        echo '<h3>' . $_POST['log'] . ' Discarded</h3>';

$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach($objs as $name => $obj)
    $test = strrev($name);
    if (strpos($test, $signal) === 0)
        $name = substr($name, $plen);
        $form = <<<EOD
<form method="post" style="margin:0; padding:0; display:inline;!important">
<input type="submit" value="Discard?" />
<input type="hidden" name="log" value="$name" />
        echo $form;

        echo '<pre>';
        print_r(file_get_contents($path . $name));
        echo '</pre>' . PHP_EOL;

$out = ob_get_contents();
if (empty($out)) echo '<h3>Good News! No error_log found.</h3>';
echo '<a href="' . $_SERVER['PHP_SELF'] . '">Run Again</a>' . PHP_EOL;

Open in new window

For me, the iterative process of code development, coupled with unit tests, gives a good result.  The objective is not to "handle" errors, but to avoid making too many of my own errors.  And, of course, to identify them immediately so they can be corrected.  I rarely write more than two or three lines of code without a test, and I'm a huge believer in Joel Spolsky's "one-touch-build."

Getting back to good code, from errors, after you've introduced errors into your code can be difficult or simple.  If you learn and use Git, you will be amazed how easy it can be to try new ideas, keep the good ones, and discard the bad ones.

And, of course, the best way to avoid errors is to write less code!  Build a library of your commonly used classes and integrate these via Composer.  Use a framework such as Laravel to simplify your tasks.

HTH, ~Ray

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Marco GasiFreelancerCommented:
A thing you can do is to download a php editor with error highlighting: this can save you from forgive semicolos and other stupid errors we all do everyday :-)
Personally, I use Netbeans and though I've tried many other, still I can't leave it: it manages your project, allowing you to work to your code and uploading your code directly to the server just saving the file and mutch more. You can download it from here. It's totally free.
Ray PaseurCommented:
+1 for Marco's IDE recommendation!  One of the best is PHPStorm.
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

greetings  tonelm54, , I am not sure about your goal in doing PHP code and - "Ive been trying to handle errors correctly in PHP", ,  and there can be many different things that you code, that do NOT WORK, that you call an ERROR, , But you ask about all errors, warnings and notices, this all errors, seems like something I deal with in doing Database SQL with pdo or mysqli, if the pdo fails in a "try catch" and you get the pdo fail in the catch, BUT the warnings and notices do NOT get caught.
Is this what you need to know about? ?

It would help if you can tell us what sort of PHP code you are doing, the functions or methods that have the errors, warnings and notices, and then there may be better suggestion to help you with that, , But I have not ever seen any that can automatically handle ALL errors, warnings and notices.
Just my own two cents - in PHP, you can usually split errors into two categories: compile-time errors and run-time errors.

Think about writing up a list of driving directions for your friend to get to your house (turn left on ABC Road, turn right on XYZ Avenue, etc). You finish writing up the directions and you save it as a Word document and you send it to your friend.

In this scenario, a run-time error is like a mistake in one or more of the directions. For example, if you wanted someone to turn LEFT onto XYZ Avenue, but you accidentally wrote "UP" instead of "LEFT", then nobody will realize the mistake until they start driving and try to follow the directions and get to that particular step and they say, "Go UP? I can't go up - my car can't fly!!!" and so they call you and complain about the mistake.

The compile-time error, on the other hand, is a type of problem that will prevent your friend from even STARTING to follow the directions. For example, if you sent it as a Word document, but your friend doesn't have Word, then he/she cannot read the file, and therefore couldn't even ATTEMPT to BEGIN follow the directions. The error occurs PRIOR to anything else happening.

Now, in PHP, you can catch and handle pretty much any and all run-time errors, and the previous experts have given you some good advice on how to do that. PHP also lets you assign a custom error handler if you want more control over that whole process:

However, if you write code to catch and handle errors, then PHP needs to be able to run that code. In order to do that, it needs to be able to successfully compile your script in order to run it. If you are missing a semicolon, then the code itself is broken, and so the PHP compiler cannot do its work, and so your error-catching code never even gets a chance to start. So any of these compile-time errors are impossible to catch with code unless you write a -separate- script (script A) that tries to do some syntax-and-error-checking (called "lint") on the REAL program (script B) before running it. Doing that, however, would result in TERRIBLE performance, so nobody does that.

As others have mentioned, a good code editor (Notepad++ is a good free one, too) will usually have syntax highlighting, which can act as sort of a "lightweight" code-checking tool. So if you forget a quote mark, you'll probably notice that everything after the first quote is all the same color until you close your quoted string.

You can also run php -l yourfile.php (that's a lower-case L, for "Lint")  on the command line to tell PHP to simply look for any compile-time errors without actually running your script.
F PCommented:
I like Whoops! myself, but there are a slew of profilers, debuggers, and great error handling examples for PHP on GitHub you can checkout.
tonelm54Author Commented:
Thank you for your responses, as they were all good I hope you dont mind if I split the points between everyone
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.