我们的 apache error_log 最近充满了类似于以下内容的行(大约 50GB):
[Wed Feb 01 16:50:15 2012] [error] [client 123.123.123.123] PHP Warning:
unpack() [<a href='function.unpack'>function.unpack</a>]:
Type V: not enough input, need 4, have 1
in /var/www/vhosts/domain.com/httpdocs/imagecreatefrombmp.php on line 52
imagecreatefrombmp.bmp中第52行如下:
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
这一行隐藏在一个 while 循环中。
如果这个问题再次发生,我希望代码安静地退出 while 循环。
问题是我无法自己复制这个问题,所以我需要盲目解决它。
我设计了以下小解决方案。它会达到目的吗?如果再次出现“Type V not input...”错误,try catch block 会捕获它并返回 false 吗?
try{
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
}catch (Exception $e) {
return FALSE;
}
最佳答案
您无法捕获 PHP 错误或警告,因为它不是异常。
您可以在调用unpack
后测试是否使用error_get_last() 引发错误。 ,但这并不实际。
另一个解决方案是 set an error handler捕获警告,然后为该警告抛出 ErrorException
。然后您将能够使用 try/catch 和 return false;
。
function my_error_handler($errno = 0, $errstr = null, $errfile = null, $errline = null) {
// If error is suppressed with @, don't throw an exception
if (error_reporting() === 0) {
return true; // return true to continue through the others error handlers
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('my_error_handler');
注意:所有错误、警告、通知等...都将转换为异常。如果您以前有过其中之一,那可能会使您的程序崩溃。
现在你可以捕获异常了:
try {
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
} catch (ErrorException $e) {
return false;
}
关于php - try catch block 用于解包功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104093/