Page 1 of 1

How to redirect and save error message on error?

Posted: Fri Apr 20, 2007 3:07 pm
by PhpMachine
Hi

When an error occures on a page (php- and mysql errors (or any error)), I want to save the error message
to a database.

Right now I have an "or die(mysql_error())" after each mysql_query() call. This displays the error directly to the user.
I'm using this when developing the website (having "display_errors = On" in php.ini).

If I now distribute the website and set "display_errors = Off", then no errors should be displayed to the
user, right?

The thing is, I want all errors to be displayed when developing, but when the website is up and running
public I want to switch off all errors and instead redirect to a 404-page where I save the error message
to a database.

Is this easily done?

Greeting

Posted: Fri Apr 20, 2007 8:56 pm
by aaronhall
set_error_handler() is your best bet, though keep in mind that it completely bypasses build-in error handling. You can use your callback function to log the error and forward the user to a different page.

Posted: Sat Apr 21, 2007 3:03 am
by PhpMachine
Hi aaronhall

I tried to use set_error_handler, but I still get a blank page with the mysql-error (die(mysql_error()).
I have set

Code: Select all

error_reporting  =  E_ALL
display_errors = Off
And at the beginning of my PHP-file, I have:

Code: Select all

set_error_handler('myErrorHandler');
function myErrorHandler($errno, $errstr, $errfile, $errline) {
 echo "error";
}
What am I doing wrong?

Posted: Sat Apr 21, 2007 6:02 am
by aaronhall
It's because die() isn't calling your error handler -- it will only execute the commands in the parentheses and "kill" the script. Since an invalid query won't throw a PHP error, you'd have to call trigger_error() inside the die() construct.

Posted: Sun Apr 22, 2007 1:02 pm
by PhpMachine
Thanks aaronhall!

It works perfectly.