2017-12-14 6 views
0

私は外部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呼び出しのみを含める必要がありますか?

+0

一般に、Exceptionをスローできるコードの部分は、 'try'ブロックでのみ必要です。 'catch'ブロックは例外を処理する手段を提供するためのものです。それ以外の場合は、実行したい操作の順序に依存しますが、これはあなたの質問ではあまり明確ではありません。 'try'ブロックのいずれかの部分がExceptionをスローすると、' return'値が到達するのを防ぐことができます。これは 'try'ブロック全体の変数に依存します。だから、私は 'try'ブロックの' return'値も移動します。 – fyrye

答えて

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ブロック内で実行されるべきであるという合理的で論理的な常識的な理由はありません。あなたのテスト。

+0

投稿したコードがクラスメソッドの一部であるため、メソッド全体をコピーしていないだけです。 – Raz

関連する問題