我使用以下函数来设置我自己的错误处理程序和异常处理程序.
set_error_handler
set_exception_handler
Run Code Online (Sandbox Code Playgroud)
错误处理程序将错误转换为异常.(引发新的例外)
但是这些异常并没有被我自己的异常处理程序捕获.
错误处理程序示例
function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) {
throw new Exception("this was an error");
}
Run Code Online (Sandbox Code Playgroud)
异常处理程序示例
function exceptionHandler($e){
// don't get here when exception is thrown in error handler
Logger::logException($e);
}
Run Code Online (Sandbox Code Playgroud)
(我认为这无论如何都行不通)
这有用吗?
或者有人可以解释为什么它不起作用?
编辑:
我做了一些测试,它应该工作.
ErrorHandler中抛出的异常被ExceptionHandler捕获并且ExceptionHandler中触发的错误正由ErrorHandler处理
仅供参考.
我的问题必须在别的地方
编辑:
我仍然没有找到为什么我的errorHandler中没有捕获我的errorHandler中抛出的异常.
例如,当我在代码中的某个地方.
trigger_error("this is an error"); // gets handled by the errorHandler
throw new Exception("this is an exception"); // gets handler by the exceptionHandler
Run Code Online (Sandbox Code Playgroud)
错误由errorHandler处理,但errorHandler中抛出的异常不会被exceptionHandler处理.
但是如果我在触发错误的同一个地方抛出异常,则异常由异常处理程序处理.
(希望以某种方式可以理解我的意思)
我在这里很无能为力.我需要寻找问题的任何想法?
这个问题已经超过2年了,但OP的观察结果是从错误处理程序抛出的一些异常无法捕获实际上是正确的:
function errorHandler($errno, $errstr, $errfile, $errline) {
throw new Exception($errstr);
}
function exceptionHandler($e) {
echo "exceptionHandler: '", $e->getMessage(), "'\n";
}
set_error_handler("errorHandler");
set_exception_handler("exceptionHandler");
// this works as expected
$a = $foo;
// this does not
$a = $foo();
Run Code Online (Sandbox Code Playgroud)
在最后一行中,实际上有两个错误在短时间内触发:
人们期望errorHandler()捕获E_NOTICE并抛出异常,然后由其处理exceptionHandler().由于exceptionHandler()永远不会返回,执行应该停在那里.
但事实并非如此:errorHandler()确实被调用并抛出其异常,但在exceptionHandler()可以做出反应之前,PHP决定退出,因为致命的E_ERROR.
这很不幸,而且我所知道的并没有非常通用的解决方案.你可以做的一件事是不是throw new Exception(...)从你的错误处理程序,而是直接调用exceptionHandler(new Exception(...)).这可以按预期工作,但缺点是您不能再出现try .. catchPHP错误.
更新2014-04-30:
这显然已在PHP 5.5中修复(或者可能是5.4,我现在无法测试).$foo和$foo()现在的行为方式相同,他们都产生输出exceptionHandler: 'Undefined variable: foo'.