php 我可以尝试/捕捉警告吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1241728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I try/catch a warning?
提问by user121196
I need to catch some warnings being thrown from some php native functions and then handle them.
我需要捕获一些 php 本机函数抛出的警告,然后处理它们。
Specifically:
具体来说:
array dns_get_record ( string $hostname [, int $type= DNS_ANY [, array &$authns [, array &$addtl ]]] )
It throws a warning when the DNS query fails.
当 DNS 查询失败时,它会发出警告。
try/catchdoesn't work because a warning is not an exception.
try/catch不起作用,因为警告不是例外。
I now have 2 options:
我现在有两个选择:
set_error_handlerseems 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.
set_error_handler似乎有点矫枉过正,因为我必须用它来过滤页面中的每个警告(这是真的吗?);调整错误报告/显示,使这些警告不会回显到屏幕上,然后检查返回值;如果是
false,则找不到主机名的记录。
What's the best practice here?
这里的最佳做法是什么?
回答by Philippe Gerber
Set and restore error handler
设置和恢复错误处理程序
One possibility is to set your own error handler before the call and restore the previous error handler later with restore_error_handler().
一种可能性是在调用之前设置您自己的错误处理程序,稍后使用restore_error_handler().
set_error_handler(function() { /* ignore errors */ });
dns_get_record();
restore_error_handler();
You could build on this idea and write a re-usable error handler that logs the errors for you.
您可以基于这个想法编写一个可重用的错误处理程序,为您记录错误。
set_error_handler([$logger, 'onSilencedError']);
dns_get_record();
restore_error_handler();
Turning errors into exceptions
将错误转化为异常
You can use set_error_handler()and the ErrorExceptionclass to turn all php errors into exceptions.
您可以使用set_error_handler()和ErrorException类将所有 php 错误转换为异常。
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
// error was suppressed with the @-operator
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
dns_get_record();
} catch (ErrorException $e) {
// ...
}
The important thing to note when using your own error handler is that it will bypass the error_reportingsetting and pass all errors (notices, warnings, etc.) to your error handler. You can set a second argument on set_error_handler()to define which error types you want to receive, or access the current setting using ... = error_reporting()inside the error handler.
使用您自己的错误处理程序时要注意的重要一点是,它将绕过error_reporting设置并将所有错误(通知、警告等)传递给您的错误处理程序。您可以设置第二个参数set_error_handler()来定义要接收的错误类型,或使用... = error_reporting()错误处理程序内部访问当前设置。
Suppressing the warning
抑制警告
Another possibility is to suppress the call with the @ operator and check the return value of dns_get_record()afterwards. But I'd advise against thisas errors/warnings are triggered to be handled, not to be suppressed.
另一种可能性是用@ 操作符抑制调用并检查之后的返回值dns_get_record()。但我建议不要这样做,因为会触发错误/警告来处理,而不是被抑制。
回答by Robert
The solution that really works turned out to be setting simple error handler with E_WARNINGparameter, like so:
真正有效的解决方案是使用E_WARNING参数设置简单的错误处理程序,如下所示:
set_error_handler("warning_handler", E_WARNING);
dns_get_record(...)
restore_error_handler();
function warning_handler($errno, $errstr) {
// do something
}
回答by GuruBob
Be careful with the @operator- while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written @mysql_query( '...' )and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but pleaseuse it with care.
小心@操作员- 虽然它会抑制警告,但也会抑制致命错误。我花了很多时间在有人编写的系统中调试问题,@mysql_query( '...' )问题是 mysql 支持没有加载到 PHP 中,它抛出了一个无声的致命错误。那些属于 PHP 核心的东西是安全的,但请小心使用。
bob@mypc:~$ php -a
Interactive shell
php > echo @something(); // this will just silently die...
No further output - good luck debugging this!
没有进一步的输出 - 祝调试好运!
bob@mypc:~$ php -a
Interactive shell
php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error: Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
bob@mypc:~$
This time we can see why it failed.
这次我们可以看到它失败的原因。
回答by sdaau
I wanted to try/catch a warning, but at the same time keep the usual warning/error logging (e.g. in /var/log/apache2/error.log); for which the handler has to return false. However, since the "throw new..." statement basically interrupts the execution, one then has to do the "wrap in function" trick, also discussed in:
我想尝试/捕获警告,但同时保留通常的警告/错误日志记录(例如 in /var/log/apache2/error.log);处理程序必须为其返回false. 但是,由于“throw new...”语句基本上会中断执行,因此必须执行“wrap in function”技巧,也讨论过:
Is there a static way to throw exception in php
Or, in brief:
或者,简而言之:
function throwErrorException($errstr = null,$code = null, $errno = null, $errfile = null, $errline = null) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
return false && throwErrorException($errstr, 0, $errno, $errfile, $errline);
# error_log("AAA"); # will never run after throw
/* Do execute PHP internal error handler */
# return false; # will never run after throw
}
...
set_error_handler('warning_handler', E_WARNING);
...
try {
mkdir($path, 0777, true);
} catch (Exception $e) {
echo $e->getMessage();
// ...
}
EDIT: after closer inspection, it turns out it doesn't work: the "return false && throwErrorException ..." will, basically, notthrow the exception, and just log in the error log; removing the "false &&" part, as in "return throwErrorException ...", will make the exception throwing work, but will then not log in the error_log... I'd still keep this posted, though, as I haven't seen this behavior documented elsewhere.
编辑:经过仔细检查,发现它不起作用:“ return false && throwErrorException ...”基本上不会抛出异常,只需登录错误日志;删除“ false &&”部分,如“ return throwErrorException ...”,将使异常抛出工作,但不会登录error_log...不过,我仍然会发布此信息,因为我没有在其他地方看到这种行为的记录。
回答by florynth
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.
通常你不应该使用@,除非这是唯一的解决方案。在这种特定情况下,应首先使用函数 dns_check_record 来了解记录是否存在。
回答by rpjohnst
You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with @ (i.e. @dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.
您可能应该尝试完全消除警告,但如果不可能,您可以在调用前加上@(即@dns_get_record(...)),然后使用您可以获得的任何信息来确定警告是否发生或不。
回答by Bugfighter
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:
围绕file_get_contents()对外部 url的调用组合这些代码行帮助我更好地处理诸如“无法打开流:连接超时”之类的警告:
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;
}
回答by Amber
If dns_get_record()fails, it should return FALSE, so you can suppress the warning with @and then check the return value.
如果dns_get_record()失败,它应该 return FALSE,所以你可以抑制警告,@然后检查返回值。
回答by Juned Ansari
FolderStructure
文件夹结构
index.php //Script File
logs //Folder for log Every warning and Errors
CustomException.php //Custom exception File
CustomException.php
自定义异常.php
/**
* Custom error handler
*/
function handleError($code, $description, $file = null, $line = null, $context = null) {
$displayErrors = ini_get("display_errors");;
$displayErrors = strtolower($displayErrors);
if (error_reporting() === 0 || $displayErrors === "on") {
return false;
}
list($error, $log) = mapErrorCode($code);
$data = array(
'timestamp' => date("Y-m-d H:i:s:u", time()),
'level' => $log,
'code' => $code,
'type' => $error,
'description' => $description,
'file' => $file,
'line' => $line,
'context' => $context,
'path' => $file,
'message' => $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'
);
$data = array_map('htmlentities',$data);
return fileLog(json_encode($data));
}
/**
* This method is used to write data in file
* @param mixed $logData
* @param string $fileName
* @return boolean
*/
function fileLog($logData, $fileName = ERROR_LOG_FILE) {
$fh = fopen($fileName, 'a+');
if (is_array($logData)) {
$logData = print_r($logData, 1);
}
$status = fwrite($fh, $logData . "\n");
fclose($fh);
// $file = file_get_contents($filename);
// $content = '[' . $file .']';
// file_put_contents($content);
return ($status) ? true : false;
}
/**
* Map an error code into an Error word, and log location.
*
* @param int $code Error code to map
* @return array Array of error word, and log location.
*/
function mapErrorCode($code) {
$error = $log = null;
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$log = LOG_ERR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$log = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$log = LOG_NOTICE;
break;
case E_STRICT:
$error = 'Strict';
$log = LOG_NOTICE;
break;
case E_DEPRECATED:
case E_USER_DEPRECATED:
$error = 'Deprecated';
$log = LOG_NOTICE;
break;
default :
break;
}
return array($error, $log);
}
//calling custom error handler
set_error_handler("handleError");
just include above file into your script file like this
只需像这样将上述文件包含到您的脚本文件中
index.php
索引.php
error_reporting(E_ALL);
ini_set('display_errors', 'off');
define('ERROR_LOG_FILE', 'logs/app_errors.log');
include_once 'CustomException.php';
echo $a; // here undefined variable warning will be logged into logs/app_errors.log
回答by gborjal
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.
尝试检查它是否返回一些布尔值,然后您可以简单地将其作为条件。我在使用 oci_execute(...) 时遇到了这个问题,它使用我的唯一键返回了一些违规行为。
ex.
oci_parse($res, "[oracle pl/sql]");
if(oci_execute){
...do something
}

