【发布时间】:2017-12-14 04:25:23
【问题描述】:
我正在开发一个处理外部 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 调用吗?
【问题讨论】:
-
一般来说,能够抛出异常的代码部分只需要在
try块中。catch块旨在为您提供一种处理异常的方法。否则这将取决于您想要完成的操作顺序,这在您的问题中不是很清楚。你所拥有的似乎很好,因为如果try块的任何部分引发异常,它将阻止达到return值,这取决于整个try块中的变量。所以我也会在try块中移动return值。