Can I try/catch a warning?

前端 未结 11 1238
孤城傲影
孤城傲影 2020-11-22 01:04

I need to catch some warnings being thrown from some php native functions and then handle them.

Specifically:

array dns_get_record  ( string $hostnam         


        
11条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:52

    Combining these lines of code around a file_get_contents() call to an external url helped me handle warnings like "failed to open stream: Connection timed out" much better:

    set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
    {
        throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
    }, E_WARNING);
    try {
        $iResult = file_get_contents($sUrl);
    } catch (Exception $e) {
        $this->sErrorMsg = $e->getMessage();
    }
    restore_error_handler();
    

    This solution works within object context, too. You could use it in a function:

    public function myContentGetter($sUrl)
    {
      ... code above ...
      return $iResult;
    }
    

提交回复
热议问题