【问题标题】:Proper way to deal with return values when using try/catch使用 try/catch 时处理返回值的正确方法
【发布时间】: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 值。

标签: php wordpress try-catch


【解决方案1】:

object 的方法被附加到 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!

这些会更合适:

  • 在类方法中添加try catch(最好)
  • 不要在附加到钩子/事件的函数中抛出异常(更好)
  • 在不是您附加的方法的新方法中抛出异常,以便您可以添加 try catch(好的,需要很好地分离关注点和抽象)
  • 添加一个全局错误处理程序(hackish,强烈建议不要这样做,这将花费比其价值更多的时间,可能会捕获您从未打算捕获的其他异常)

否则,没有合理、合乎逻辑、常识的理由说明 throw new \Exception 的代码行应该像上面那样在 try catch 块内执行,而无需像在测试中那样有目的地手动调用它。

【讨论】:

  • 我不确定我是否遵循 - 发布的代码是类方法的一部分,我只是没有复制整个方法。
  • 答案是从这里复制粘贴的,没有归功于作者。 wordpress.stackexchange.com/a/137112
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2019-04-23
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多