使用try / catch时处理返回值的正确方法

I am working on a wordpress plugin that deals with an external API. I want to use a try/catch block for the API call but I am not sure if the way I am dealing with the return value is ok.

try {
            $response = wp_remote_post($url,$args);

            $communication_location = wp_remote_retrieve_header( $response, 'location' );
            $communication_location_arr = explode('/', $communication_location);

            $communication_id = end($communication_location_arr);
            $response_code = wp_remote_retrieve_response_code($response);

        }

        catch (Exception $e){
            throw new Exception('Something went wrong when trying to create the communication');
        }

        return array(0 => $response_code,1 => $communication_id);

Should the try block only contain the wp_remote_post call?

The methods of object are attached to the init action hook, and are thrown when the init hook is fired, not when the object is created, and not when they're attached.

class SomeClass {
    public function __construct() {
        // when the init action/event happens, call the wp_some_method
        add_action( 'init', array( $this, 'wp_some_method' ) );
    }
    function wp_some_method( $post_type ){
        throw new \Exception('error'); 
    }
}
try{
    // great, no exceptions where thrown while creating the object
    $o = new SomeClass();    
} catch (\Exception $ex) {
    echo $ex->getMessage();
}

// a small period of time later somewhere in WP Core...

do_action( 'init' ); // a method we attached to the init hook threw an exception, but nothing was there to catch it!

These would be more appropriate:

  • add a try catch in the class methods ( best )
  • Don't throw exceptions in functions attached to hooks/events ( even better )
  • throw the exception in a new method that isn't the method you attached so you can add in a try catch ( okay, requires good separation of concerns and abstraction )
  • add a global error handler ( hackish, strongly advise against, will take more time than its worth, may catch other exceptions that you never intended to catch )

Otherwise there is no rational, logical, common sense reason why the line of code that says throw new \Exception should be executed inside the try catch block as you have above without you purposefully calling it manually as you did in your test.

</div>