Re: Making PEAR_ErrorStack throw PHP5 exceptions
| From: | Greg Beaver | Date: | Mon, 22 Nov 2004 02:44:35 +0000 |
| Subject: | Re: Making PEAR_ErrorStack throw PHP5 exceptions | ||
| References: | 1 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-15749@lists.php.net to get a copy of this message | ||
Will Bryant wrote:
Hi all, I've been using the DB API. Now that I'm moving to PHP5, I'd like to get it throwing exceptions instead of returning error objects. While the documentation suggests that this should work, I'm having trouble getting PEAR_ErrorStack to do this. http://pear.php.net/manual/en/core.pear.pear-errorstack.intro.php suggests this: <?php require_once 'PEAR/ErrorStack.php'; $stack = &PEAR_ErrorStack::singleton('mypackage', false, null, 'PEAR_ErrorStack', false, 'MyException'); ?> But (after changing MyException to say 'PEAR_Error') this doesn't seem to do anything - it runs, but errors are still returned in the usual way, no exception is thrown. Similarly "PEAR_ErrorStack::singleton('DB', false, false, false, 'PEAR_Error')", which is what I think the 'singleton' method documentation says I should be using, has no effect. Is there something else I need to do to set it up to throw exceptions, or is the documented syntax not correct?Hi Will, as of PEAR 1.3.2, you have to manually re-package errors as exceptions and throw them - check the docs again for details. There are many reasons for this, but the extra steps are simple. The only question is how you want DB to throw the exceptions. If you use *any* other packages that use PEAR::raiseError(), you could seriously muck things up. Otherwise, use a callback <?php require_once 'PEAR.php'; require_once 'PEAR/ErrorStack.php'; $stack = PEAR_ErrorStack::singleton('PEAR_Error'); $stack->pushCallback('throwme'); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'catchPEAR'); class DBException extends Exception {} function throwme($err) {
throw new DBException($err['message'], $err['code']);} function catchPEAR($err) {
$stack = PEAR_ErrorStack::singleton('PEAR_Error');
$stack->push($err->getCode(), 'exception', array('PEAR_Error' => $err), $err->getMessage());
}
?>
Of course, you can customize the DBException to include the original PEAR_Error object if you would like. However, far simpler for your purposes is to simply use a PEAR_Error callback
<?php
require_once 'PEAR.php';
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'catchPEAR');
class DBException extends Exception {}
function catchPEAR($err)
{
throw new DBException($err->getMessage(), $err->getCode();} ?> Greg