对file_get_contents进行异常捕获


        项目中,需要用到调用其他组的接口,目前这边就封装了个函数来实现

function file_get_contents_post($url, $post)
{
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => http_build_query($post),
        ),
    );

    $result = file_get_contents($url, false, stream_context_create($options));

    return $result;
}

        正确调用是没问题的,但是如果对方服务平台不稳定了,PHP便会报错,停在那了,于是便加了个异常捕获

function run()
{
    set_error_handler(
        create_function(
            '$severity, $message, $file, $line',
            'throw new ErrorException($message, $severity, $severity, $file, $line);'
        )
    );
    
    try {
        file_get_contents_post('http://url/', []);
    }
    catch (Exception $e) {
        echo $e->getMessage();
    }

    restore_error_handler();
}

run();


你可能感兴趣的:(PHP)