Can I try/catch a warning?

2018-12-31 04:23发布

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

Specifically:

array dns_get_record  ( string $hostname  [, int $type= DNS_ANY  [, array &$authns  [, array &$addtl  ]]] )

It throws a warning when the DNS query fails.

try/catch doesn't work because a warning is not an exception.

I now have 2 options:

  1. set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);

  2. Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.

What's the best practice here?

10条回答
ら面具成の殇う
2楼-- · 2018-12-31 05:10

If dns_get_record() fails, it should return FALSE, so you can suppress the warning with @ and then check the return value.

查看更多
爱死公子算了
3楼-- · 2018-12-31 05:14

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;
}
查看更多
不再属于我。
4楼-- · 2018-12-31 05:18

try checking whether it returns some boolean value then you can simply put it as a condition. I encountered this with the oci_execute(...) which was returning some violation with my unique keys.

ex.
oci_parse($res, "[oracle pl/sql]");
if(oci_execute){
...do something
}
查看更多
心情的温度
5楼-- · 2018-12-31 05:24

Normaly you should never use @ unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.

查看更多
登录 后发表回答