使用preg_match时如何捕获异常?

时间:2019-04-16 13:44:55

标签: php exception

我有以下代码,除了找不到模式和引发异常外,其他代码都可以正常工作。如何捕获此错误?请帮助...

function GetUser($username) {
    $options  = array('http' => array('user_agent' => 'some_obscure_browser'));
    $context  = stream_context_create($options);
    $site = file_get_contents('https://www.example.com/' . $username, false, $context);

    $pattern = '/\"entity_id\":\"(\d+)\"/';

    if (!preg_match($pattern, $site, $matches)) {
        throw new Exception('User not found');
    }
    return $matches[1];
  }

错误消息

  

警告:file_get_contents(https://www.example.com/wrong_pattern):打开流失败:HTTP请求失败!在第23行的D:\ XAMPP \ htdocs \ site \ test.php中找不到HTTP / 1.1 404

     

致命错误:未捕获的异常:file_get_contents(https://www.example.com/wrong_pattern):无法打开流:HTTP请求失败!在D:\ XAMPP \ htdocs \ site \ test.php:36中找不到HTTP / 1.1 404堆栈跟踪:#0 D:\ XAMPP \ htdocs \ site \ test.php(48):GetUser('wrong_pattern')#1 {main}在第36行的D:\ XAMPP \ htdocs \ site \ test.php中抛出

1 个答案:

答案 0 :(得分:0)

将所有内容放入try / catch块中,如果引发了错误,则

try {
    // your current code here
} catch( Exception $e ) {
    echo $e->getMessage();
    // Or different way of handling that problem - depends on your needs
}