[英]php - How to catch an unexpected error?
我正在编写一个脚本,很多东西都可能出错。 我正在为明显的事情制作if / else语句,这可能会引起注意,但有没有办法捕捉到某些东西,这可能会导致麻烦,但我不知道它到底是什么?
例如,在脚本中间会出现某种错误。 我想通知用户,出现了问题,但没有几十个php警告脚本。
我需要类似的东西
-- start listening && stop error reporting --
the script
-- end listening --
if(something went wrong)
$alert = 'Oops, something went wrong.';
else
$confirm = 'Everything is fine.'
谢谢。
为什么不试试......赶上?
$has_errors = false;
try {
// code here
} catch (exception $e) {
// handle exception, or save it for later
$has_errors = true;
}
if ($has_errors!==false)
print 'This did not work';
编辑:
下面是set_error_handler
的示例,它将处理在try ... catch块的上下文之外发生的任何错误。 如果PHP配置为显示通知,这也将处理通知。
基于以下代码: http : //php.net/manual/en/function.set-error-handler.php
set_error_handler('genericErrorHandler');
function genericErrorHandler($errno, $errstr, $errfile, $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
$v = 10 / 0 ;
die('here');
阅读Exceptions
:
try {
// a bunch of stuff
// more stuff
// some more stuff
} catch (Exception $e) {
// something went wrong
}
throw new Exception('Division by zero.');
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
您绝对应该使用try-catch语法来捕获脚本抛出的任何异常。
此外,您可以扩展异常并实现满足您需求的新异常 。这样,当您发现任何其他类型的意外错误(脚本逻辑错误)时,您可以抛出自己的异常。
一个非常简短的例子,解释了扩展异常的使用:
//your own exception class
class limitExceededException extends Exception { ... }
try{
// your script here
if($limit > 10)
throw new limitExceededException();
}catch(limitExceededException $e){//catching only your limit exceeded exception
echo "limit exceeded! cause : ".$e->getMessage();
}catch(Exception $e){//catching all other exceptions
echo "unidentified exception : ".$e->getMessage();
}
除了使用try / catch之外,我认为重要的是要考虑是否应该捕获意外错误。 如果它是意外的,那么您的代码不知道如何处理它并允许应用程序继续可能产生错误的数据或其他不正确的结果。 最好让它崩溃到错误页面。 我最近遇到了一个问题,其中有人为所有内容添加了通用异常处理程序,并且它隐藏了异常的原始位置,使得很难找到错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.