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:
set_error_handler
seems like overkill because I have to use it to filter every warning in the page (is this true?);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?
If
dns_get_record()
fails, it should returnFALSE
, so you can suppress the warning with@
and then check the return value.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:This solution works within object context, too. You could use it in a function:
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.
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.