php-如何捕获意外错误?

Mik*_*ike 2 php try-catch

我正在写一个脚本,很多事情都可能出错。我正在针对可能的东西进行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.'
Run Code Online (Sandbox Code Playgroud)

谢谢。

Chr*_*ker 6

为什么不尝试...赶上?

$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';
Run Code Online (Sandbox Code Playgroud)

编辑:

这是的示例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'); 
Run Code Online (Sandbox Code Playgroud)

  • 不应该。通常,人们会关闭生产服务器上的通知。也就是说,除了捕获try ... catch之外发生的任何事情之外,您还可以使用set_error_handler。如果您确实启用了这些通知,则将包括这些通知(同样,在生产环境中不建议这样做)。有关更多信息,请参见PHP文档:http://php.net/manual/en/function.set-error-handler.php (3认同)