我正在处理一个处理外部API的wordpress插件。我想在API调用中使用try / catch块,但我不确定我处理返回值的方式是否正常。
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);
try块是否只包含wp_remote_post调用?
答案 0 :(得分:1)
对象的方法附加到init动作钩子,并且在触发init钩子时抛出,而不是在创建对象时抛出,而不是在它们被附加时抛出。
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!
这些更合适:
否则没有合理的,逻辑的,常识性的理由为什么抛出new \ Exception的代码行应该像你在上面那样在try catch块中执行,而你没有像在测试中那样有目的地手动调用它。