Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm creating a new plugin and I want to handle errors cleanly. I find the WP_Error class unwieldy so have decided to use exceptions. I am not bothered about lack of PHP 4 support.

$error = true;
if ($error) {
    // Throw an error
    throw new CustomException('A custom exception');
}

What I really want to be able to do is throw exceptions as per the code above in my plugin (and use try/catch blocks where appropriate), but when there is an uncaught exception, I want to be able to set an error handler ie:set_exception_handler() that only catches uncaught exceptions from my plugin. So if another theme exception handler has been set already, it doesn't interfere.

Even better would be if I intercepted any of my plugin exceptions, dealt with them as appropriate, and then could choose to forward them onto any other already set exception handlers.

Is this possible? Or is it possible to set an exception handler that only catches exceptions from within the class it is set? I was thinking along the lines of creating a customException that extended Exception and then somehow having a custom catch-all exception handler for it.

share|improve this question

2 Answers 2

You can also extend expections and then catch only those that you throw.

For example:

function do_add_my_pws_exceptions() {
   class PWS_Exception extends Exception {}
   class PWS_Init_Exception extends PWS_Exception {}
}
add_action('plugins_loaded', 'do_add_my_pws_exceptions');

Of course, you should be certain the user is running at least version 5 of PHP by having your theme of plugin activation do something like the following:

$php_version = phpversion();
if ( version_compare( $php_version, '5.3', '<' ) ) {
    # deactivate your plugin or abort installing your theme and tell the user why
}

Anywise, once that is done, you can then do things like:

try {
   # whatever you are doing
   throw new PWS_Exception("This is my exception", 10001);
} catch ( PWS_Exception $e ) {
   # Your custom handling
}

Any exceptions not thrown by you will not be caught.

share|improve this answer

When you use set_exception_handler it returns the name of the previous exception handler. You can store that and use it with call_user_func or just use the () syntax.

http://us.php.net/manual/en/function.set-exception-handler.php

$prev_handler = set_exception_handler('my_handler');
call_user_func($prev_handler, $exception);
# OR
$prev_handler($exception);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.