如何检索当前的错误处理程序?

问题描述 投票:0回答:7

我想了解当前正在处理错误的错误处理程序。

我知道

set_error_handler()
将返回上一个错误处理程序,但是有没有一种方法可以在不设置新错误处理程序的情况下找出当前错误处理程序是什么?

php
7个回答
26
投票

尽管 PHP 中缺少

get_error_handler()
函数,但您可以使用
set_error_handler()
的一些技巧来检索当前的错误处理程序,尽管您可能无法利用该信息做很多事情,具体取决于它的值。尽管如此:

set_error_handler($handler = set_error_handler('var_dump'));
// Set the handler back to itself immediately after capturing it.

var_dump($handler); // NULL | string | array(2) | Closure

看,妈妈,它是幂等的!


16
投票

是的,有一种方法可以找到错误处理程序,而无需设置新的错误处理程序。这不是一步本地 php 函数。但它的效果正是你所需要的。

总结@aurbano、@AL the X、@Jesse 和@Dominic108 的所有建议替换方法可以如下所示

function get_error_handler(){
    $handler = set_error_handler(function(){});
    restore_error_handler();
    return $handler;
}

6
投票

您可以使用

set_error_handler()
set_error_handler()
返回当前错误处理程序(尽管为“混合”)。检索后,使用
restore_error_handler()
,它会保持原样。


5
投票

这在 PHP 中是不可能的 - 正如您所说,您可以在调用 set_error_handler 时检索当前的错误处理程序并使用 Restore_error_handler 恢复它


0
投票
<?php

class MyException extends Exception {}

set_exception_handler(function(Exception $e){
    echo "Old handler:".$e->getMessage();
});

$lastHandler = set_exception_handler(function(Exception $e) use (&$lastHandler) {
    if ($e instanceof MyException) {
        echo "New handler:".$e->getMessage();
        return;
    }

    if (is_callable($lastHandler)) {
        return call_user_func_array($lastHandler, [$e]);
    }

    throw $e;
});

触发异常处理程序:

throw new MyException("Exception one", 1);

输出:

New handler:Exception one

throw new Exception("Exception two", 1);

输出:

Old handler:Exception two


0
投票

您还可以使用此代码示例来获取最后一个异常处理程序:

function get_exception_handler()
{
    $handler = set_exception_handler(function () {});
    restore_exception_handler();
    return $handler;
}

如果您想要 - 例如在单元测试中 - 已注册哪个异常处理程序,这可能很有用。


-4
投票

我检查了来源,答案是否定的。

© www.soinside.com 2019 - 2024. All rights reserved.