私は外部APIを扱うwordpressプラグインを開発しています。私は、API呼び出しのtry/catchブロックを使用したいが、返り値を扱っている方法が問題ないかどうかはわかりません。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呼び出しのみを含める必要がありますか?
一般に、Exceptionをスローできるコードの部分は、 'try'ブロックでのみ必要です。 'catch'ブロックは例外を処理する手段を提供するためのものです。それ以外の場合は、実行したい操作の順序に依存しますが、これはあなたの質問ではあまり明確ではありません。 'try'ブロックのいずれかの部分がExceptionをスローすると、' return'値が到達するのを防ぐことができます。これは 'try'ブロック全体の変数に依存します。だから、私は 'try'ブロックの' return'値も移動します。 – fyrye