unknown exception error in php-Collection of common programming errors
i wanna catch all exceptions thrown in a script and then check if they have a error code 23000.
if they don’t i want to rethrow the exception.
here is my code:
function myException($exception) {
/*** If it is a Doctrine Connection Mysql Duplication Exception ***/
if(get_class($exception) === 'Doctrine_Connection_Mysql_Exception' && $exception->getCode() === 23000) {
echo "Duplicate entry";
} else {
throw $exception;
}
}
set_exception_handler('myException');
$contact = new Contact();
$contact->email = 'peter';
$contact->save();
but i get this error message and i dont know what it means:
Fatal error: Exception thrown without a stack frame in Unknown on line 0
i want to be able to rethrow the original error message if it has not the error code 23000.
even when i deleted the check errorcode i still get the same message:
function myException($exception) {
throw $exception;
}
set_exception_handler('myException');
$contact = new Contact();
$contact->email = 'peter';
$contact->save();
how could i solve this?
thanks
-
Don’t use the exception handler for this.
The exception handler is only the “last resort” to handle uncaught exceptions.
You can’t throw a new exception within it – it would lead to an infinite loop.
The regular way to handle exceptions is using a
try... catch {}
block:try { $contact->save(); } catch (Exception $exception) { if(get_class($exception) === 'Doctrine_Connection_Mysql_Exception' && $exception->getCode() === 23000) { echo "Duplicate entry"; } else { throw $exception; // throw it on if it's not a doctrine exception // (if that's what you want) } }
I know this looks way more messy than the way you do it. That’s why I’m not really fond of exceptions.
-
i’m not sure but try this code
function myException($exception) { restore_exception_handler(); throw $exception; } //you can set here another exception handler that will be restored. //or your exception will be thrown to standard handler //set_exception_handler('myException2'); set_exception_handler('myException'); $contact = new Contact(); $contact->email = 'peter'; $contact->save();
Originally posted 2013-11-10 00:11:25.