【问题标题】:How to set PHP set_error_handler correctly如何正确设置 PHP set_error_handler
【发布时间】:2016-11-13 13:52:28
【问题描述】:

你能帮我正确设置 php set_error_handler 吗?我需要处理抛出 php warning as exception 的代码。但我不知道如何正确地做到这一点。现在我有这段代码,我认为这是不正确的。

set_error_handler( function( $errno, $errstr, $errfile, $errline, array $errcontext )
{
    throw new \Exception( $errstr, $errno );
});
$mailer->send( $mail );
restore_error_handler(); 

正如我在documentation 中看到的,它需要更复杂的解决方案。但我对所有这些常数有点困惑。 有没有办法以某种优雅的方式设置它,不会单独设置所有常量。 我的意思是:

function( $errno, $errstr, $errfile, $errline, array $errcontext )
{
    if( $errno >= E_USER_WARNING ) throw new \Exception( $errstr, $errno );
});

那么如何以某种优雅的方式将 php 警告包含到异常中。谢谢。

【问题讨论】:

    标签: php error-handling custom-error-handling


    【解决方案1】:

    所以在我的例子中,errno 必须有一个条件并且它必须返回 true。

    set_error_handler( function( $errno, $errstr, $errfile, $errline, array $errcontext )
    {
        // Cause Php does not catch stream_socket_client warnings message.
        if ( $errno == E_WARNING ) throw new \Exception( $errstr, $errno ); 
        // Is necessary to handle other errors by default handler.
        return true; 
    }); 
    

    【讨论】:

      猜你喜欢
      • 2011-09-07
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2018-04-02
      相关资源
      最近更新 更多