gpt4 book ai didi

PHP:如何使用 set_error_handler() 正确处理除通知之外的所有错误?

转载 作者:IT王子 更新时间:2023-10-28 23:53:56 26 4
gpt4 key购买 nike

我对如何正确使用 set_error_handler() 以及 php documentation 感到困惑并没有真正帮助澄清。

我希望它通过电子邮件向我发送尽可能多的错误,但通知除外。

我有以下代码

<?php

if (TRAP_ERRORS) {
// True on production, false in development, where errors are just echoed out.
set_exception_handler('globalExceptionHandler');
set_error_handler('globalErrorHandler', E_USER_WARNING);
}

function globalExceptionHandler($e) {
//log and email stuff here
}

function globalErrorHandler($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$errors = "Notice";
break;
case E_WARNING:
case E_USER_WARNING:
$errors = "Warning";
break;
case E_ERROR:
case E_USER_ERROR:
$errors = "Fatal Error";
break;
default:
$errors = "Unknown Error";
break;
}

error_log(sprintf("PHP %s: %s in %s on line %d", $errors, $errstr, $errfile, $errline));
$msg = "ERROR: [$errno] $errstr\r\n".
"$errors on line $errline in file $errfile\r\n";

sendErrorEmail($msg);
showErrorPage();

exit(1);
}

function sendErrorEmail($p_errorMsg) {
// Parse and sent out the error email...
}

function showErrorPage() {
// Redirect to an error page.
}

?>

上面是我当前的设置 set_error_handler('globalErrorHandler', E_USER_WARNING);,这似乎是错误的,因为它没有涵盖 trigger_error() 错误。我相信这是因为该参数应该是一个位掩码,而不仅仅是一个错误级别,但我不确定如何将它设置为适用于最大数量的错误/信息(通知除外)。我见过使用 E_ALL 的示例,但这实际上会直接导致任何包含全局错误处理程序内容的代码对我来说出错。

那么无论如何,我该如何使用 set_error_handler 以便我的自定义错误处理程序可以处理最大量的信息(这样我就可以在出现此类问题时直接收到自动电子邮件,而不必稍后查看日志)。

最佳答案

set_error_handler('some_handler',E_ALL & ~E_NOTICE & ~E_USER_NOTICE);

或者,如果你真的想要全部,

set_error_handler('some_handler',-1 & ~E_NOTICE & ~E_USER_NOTICE);

或者,您可以将它设置为使用所有错误,如果它们不在 error_reporting 中(您将其设置为与上述行相同的值,并且 @ 运算符然后工作):

....
if(!($errno & error_reporting())) return true;
switch($errno){
....

关于PHP:如何使用 set_error_handler() 正确处理除通知之外的所有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6217994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com