For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > April 2005 > Generic error/exception handler









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Generic error/exception handler
Csaba Gabor

2005-04-28, 8:56 pm

I seem to have messed up on what I posted to you. Here is example code
that does what I was looking for - a generic catch all (or at least
catch most) error handler for PHP5. The point is that I did not want
to test for errors, nor throw exceptions. I just want to catch all
errors/exceptions that happen so I can deal with them gracefully.

<?
// see http://php.net/error_reporting
error_reporting(E_ALL);

// see http://php.net/set_error_handler
function myErrorHandler($errno, $errstr, $errfile, $errline) {
// a fifth argument (context) is passed, whether defined or not
print "Standard error in line $errline:";
print "<br>\n$errstr\n<br>";
}
set_error_handler('myErrorHandler');

// see http://php.net/exceptions
try {
$foo = 7 / 0; // execution resumes after a warning
$bar = new COM("speling.error"); // exception is thrown
// exception thrown above => line below not executed
print "<br>\nThird line of the try";
} catch (Exception $e) { // generic exception handler
print "<br>\nThrown exeption in line " . $e->getLine();
print "<br>\n" . $e->getMessage() . "\n<br>";
}
print "<br>\nEnd of routine";
?>

Csaba Gabor from Vienna

NC

2005-04-28, 8:56 pm

Csaba Gabor wrote:
>
> I just want to catch all errors/exceptions that happen
> so I can deal with them gracefully.


Well, at this point, an error and an exception are different
beasts and must be handled differently. You can, however, try
combining two handlers into one:

function handleItAll ($arg1, $arg2=NULL, $arg3=NULL, $arg4=NULL) {
if (is_object($arg1)) {
// exception thrown; handle it
}
if (is_numeric($arg1)) {
// error triggered; handle it
}
}

set_error_handler('handleItAll');
set_exception_handler('handleItAll');

Cheers,
NC

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com