douxiongye5779 2017-12-14 04:25
浏览 1026

使用try / catch时处理返回值的正确方法

I am working on a wordpress plugin that deals with an external API. I want to use a try/catch block for the API call but I am not sure if the way I am dealing with the return value is ok.

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);

Should the try block only contain the wp_remote_post call?

  • 写回答

1条回答 默认 最新

  • dty98339 2017-12-14 06:00
    关注

    The methods of object are attached to the init action hook, and are thrown when the init hook is fired, not when the object is created, and not when they're attached.

    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!

    These would be more appropriate:

    • add a try catch in the class methods ( best )
    • Don't throw exceptions in functions attached to hooks/events ( even better )
    • throw the exception in a new method that isn't the method you attached so you can add in a try catch ( okay, requires good separation of concerns and abstraction )
    • add a global error handler ( hackish, strongly advise against, will take more time than its worth, may catch other exceptions that you never intended to catch )

    Otherwise there is no rational, logical, common sense reason why the line of code that says throw new \Exception should be executed inside the try catch block as you have above without you purposefully calling it manually as you did in your test.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?