[wp-trac] [WordPress Trac] #16769: Make WP_Error extending Exception to make it throw-able

WordPress Trac wp-trac at lists.automattic.com
Tue Mar 8 14:20:46 UTC 2011


#16769: Make WP_Error extending Exception to make it throw-able
-------------------------+-----------------------------
 Reporter:  hakre        |       Owner:
     Type:  enhancement  |      Status:  reopened
 Priority:  lowest       |   Milestone:  Future Release
Component:  General      |     Version:  3.1
 Severity:  normal       |  Resolution:
 Keywords:               |
-------------------------+-----------------------------

Comment (by filosofo):

 Replying to [comment:8 westi]:
 > The real bug is that nothing actually checks for the WP_Error that is
 returned.

 One of the great things about thrown exceptions is that you can reduce the
 number of error checks.  Currently we have an error-checking structure
 roughly like this:

 {{{
 function a (){
    $b = b();
    if ( is_wp_error( $b ) ) {
       return $b;
    } else {
       $c = c( $b );
       if ( is_wp_error( $c ) ) {
          return $c;
       } else {
          echo $c->property;
       }
 }
 function b (){...}
 function c (){...}

 $result = a();
 if ( is_wp_error( $result ) ) {
    echo $result->get_error_message();
 }

 }}}

 With thrown exceptions, we never have to check whether the returned object
 is an error object.  PHP takes care of that for us:

 {{{
 function a (){
    $b = b();
    $c = c( $b );
    echo $c->property;
 }
 function b (){...}
 function c (){...}

 try {
    $result = a();
 } catch( WP_Exception $err ) {
    echo $result->getMessage();
 }
 }}}

 The second example is easier to grok and does less work to achieve the
 same result.

 > Switching to throwing the Error Object instead makes it harder to track
 error handling correctly in my experience.

 One simple thing we can do to address that is have different exception
 classes for different code purposes, and throw the relevant kind of
 exception:

 {{{
 class WP_DB_Exception extends WP_Exception {}
 class WP_Taxonomy_Exception extends WP_Exception {}
 class WP_Capabilities_Exception extends WP_Exception {}
 }}}
 So you might show a WP_DB_Exception message only when in debug mode, but
 always show the WP_Capabilities_Exception.  (These aren't great examples
 but you get the idea.)


 And there is the Exception `getTrace` method if you really want to track
 the origin of the Exception in the code.

-- 
Ticket URL: <http://core.trac.wordpress.org/ticket/16769#comment:10>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software


More information about the wp-trac mailing list