2

包括的なエラー処理の実装を試みる試みを数多く見つけたので、できれば思いついた完全な解決策を提供するために wiki スタイルを作成するかもしれないと考えました。

質問は:

「PHP ですべての種類のエラーをキャッチ、処理、またはインターセプトするにはどうすればよいでしょうか?」

さて、これは「書き直し」と見なされる人もいるかもしれませんが、包括的な解決策が提案されているかどうかはわかりません。

4

3 に答える 3

4

PHP エラーにはいくつかのレベルがあり、そのうちのいくつかは個別のエラー ハンドラーを設定する必要があり、PHP がスローする可能性のあるすべてのエラーをキャッチするには、エラーのこれらの「タイプ」をすべて網羅するものを作成する必要があります。ランタイム」、および例外。

パイプを下るすべての(私が知る限り)エラーをキャッチする私の解決策:

  • いくつかのグローバル変数
  • 初期化方法
  • 4 つの「非 OOP」エラー ハンドラ メソッド
  • 「AppendError」メソッドを持つ ErrorHandler クラス - エラーが出力されるかどうかを正確に変更できる場所です (この場合、エラーはこのメソッドから最小限の HTML で画面にダンプされます)。

...

// Moved this line to the bottom of the 'file' for usability - 
// I keep each of the above mentioned 'pieces' in separate files.
//$ErrorHandler = new ErrorHandler();

$ErrorCallback = "HandleRuntimeError";
$ExceptionCallback = "HandleException";
$FatalCallback = "HandleFatalError";

$EnableReporting = true;
$ErrorLevel = E_ALL;

function InitializeErrors()
{
    if($GLOBALS["EnableReporting"])
    {
        error_reporting($GLOBALS["ErrorLevel"]);

        if( isset($GLOBALS["ErrorCallback"]) && strlen($GLOBALS["ErrorCallback"]) > 0 )
        {
            set_error_handler($GLOBALS["ErrorCallback"]);

            // Prevent the PHP engine from displaying runtime errors on its own
            ini_set('display_errors',false);
        }
        else
            ini_set('display_errors',true);

        if( isset($GLOBALS["FatalCallback"]) && strlen($GLOBALS["FatalCallback"]) > 0 )
        {
            register_shutdown_function($GLOBALS["FatalCallback"]);

            // Prevent the PHP engine from displaying fatal errors on its own
            ini_set('display_startup_errors',false);
        }
        else
            ini_set('display_startup_errors',true);

        if( isset($GLOBALS['ExceptionCallback']) && strlen($GLOBALS['ExceptionCallback']) > 0 )
            set_exception_handler($GLOBALS["ExceptionCallback"]);
    }
    else
    {
        ini_set('display_errors',0);
        ini_set('display_startup_errors',0);
        error_reporting(0);
    }
}

function HandleRuntimeError($ErrorLevel,$ErrorMessage,$ErrorFile=null,$ErrorLine=null,$ErrorContext=null)
{
    if( isset($GLOBALS['ErrorHandler']))
    {
        //  Pass errors up to the global ErrorHandler to be later inserted into
        // final output at the appropriate time.
        $GLOBALS['ErrorHandler']->AppendError($ErrorLevel,"Runtime Error: " . $ErrorMessage,$ErrorFile,$ErrorLine,$ErrorContext);

        return true;
    }
    else
    {
        PrintError($ErrorLevel,$ErrorMessage,$ErrorFile,$ErrorLine,$ErrorContext);
        return true;
    }
}

function HandleException($Exception)
{
    if( isset($GLOBALS['ErrorCallback']))
    {
        // Parse and pass exceptions up to the standard error callback.
        $GLOBALS['ErrorCallback']($Exception->getCode(), "Exception: " . $Exception->getMessage(), $Exception->getFile(), $Exception->getLine(), $Exception->getTrace());

        return true;
    }
    else
    {       
        PrintError($Exception->getCode(), "Exception: " . $Exception->getMessage(), $Exception->getFile(), $Exception->getLine(), $Exception->getTrace());
        return true;
    }
}

function HandleFatalError()
{
    $Error = error_get_last();

    // Unset Error Type and Message implies a proper shutdown.
    if( !isset($Error['type']) && !isset($Error['message']))
        exit();
    else if( isset($GLOBALS['ErrorCallback']))
    {
        // Pass fatal errors up to the standard error callback.
        $GLOBALS["ErrorCallback"]($Error['type'], "Fatal Error: " . $Error['message'],$Error['file'],$Error['line']);

        return null;
    }
    else
    {
        PrintError($Error['type'], "Fatal Error: " . $Error['message'],$Error['file'],$Error['line']);
        return null;
    }
}

// In the event that our 'ErrorHandler' class is in fact the generator of the error,
// we need a plain-Jane method that will still deliver the message.
function PrintError($ErrorLevel,$ErrorMessage,$ErrorFile=null,$ErrorLine=null,$ErrorContext=null)
{
    if( class_exists("ErrorHandler"))
        $ErrorTypeString = ErrorHandler::ErrorTypeString($ErrorLevel);
    else
        $ErrorTypeString = "$ErrorLevel";

    if( isset($ErrorContext) && !is_array($ErrorContext) && strlen($ErrorContext) > 0 )
        $ErrorContext = str_replace("#", "<br/>\r\n#", $ErrorContext);

    $ReturnValue = "";
    $ReturnValue .= "<div class=\"$ErrorTypeString\" style=\"margin: 10px;\">\r\n";

    $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Error Level:</span> <span class=\"ErrorValue\">$ErrorTypeString</span></p>\r\n";

    if( isset($ErrorFile) && strlen($ErrorFile) > 0 )
        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">File:</span> <span class=\"ErrorValue\">'$ErrorFile'</span></p>\r\n";

    if( isset($ErrorLine) && strlen($ErrorLine) > 0 )
        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Line:</span> <span class=\"ErrorValue\">$ErrorLine</span></p>\r\n";

    if( isset($ErrorContext) && is_array($ErrorContext))
        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Context:</span><span class=\"ErrorValue\">" . var_export($ErrorContext,true) . "</span></p>\r\n";
    else if( isset($ErrorContext) && strlen($ErrorContext) > 0 )
        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Context:</span><span class=\"ErrorValue\">$ErrorContext</span></p>\r\n";

    $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Message:</span> <span class=\"ErrorValue\">" . str_replace("\r\n","<br/>\r\n",$ErrorMessage) . "</span></p>\r\n";

    $ReturnValue .= "</div>\r\n";

    echo($ReturnValue);
}

class ErrorHandler
{   
    public function AppendError($ErrorLevel,$ErrorMessage,$ErrorFile=null,$ErrorLine=null,$ErrorContext=null)
    {
        // Perhaps evaluate the error level and respond accordingly
        //
        // In the event that this actually gets used, something that might 
        // determine if you're in a production environment or not, or that 
        // determines if you're an admin or not - or something - could belong here.
        // Redirects or response messages accordingly.
        $ErrorTypeString = ErrorHandler::ErrorTypeString($ErrorLevel);

        if( isset($ErrorContext) && !is_array($ErrorContext) && strlen($ErrorContext) > 0 )
            $ErrorContext = str_replace("#", "<br/>\r\n#", $ErrorContext);

        $ReturnValue = "";
        $ReturnValue .= "<div class=\"$ErrorTypeString\" style=\"margin: 10px;\">\r\n";

        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Error Level:</span> <span class=\"ErrorValue\">$ErrorTypeString</span></p>\r\n";

        if( isset($ErrorFile) && strlen($ErrorFile) > 0 )
            $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">File:</span> <span class=\"ErrorValue\">'$ErrorFile'</span></p>\r\n";

        if( isset($ErrorLine) && strlen($ErrorLine) > 0 )
            $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Line:</span> <span class=\"ErrorValue\">$ErrorLine</span></p>\r\n";

        if( isset($ErrorContext) && is_array($ErrorContext))
            $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Context:</span><span class=\"ErrorValue\">" . var_export($ErrorContext,true) . "</span></p>\r\n";
        else if( isset($ErrorContext) && strlen($ErrorContext) > 0 )
            $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Context:</span><span class=\"ErrorValue\">$ErrorContext</span></p>\r\n";

        $ReturnValue .= "<p class=\"ErrorData\"><span class=\"ErrorKey\">Message:</span> <span class=\"ErrorValue\">" . str_replace("\r\n","<br/>\r\n",$ErrorMessage) . "</span></p>\r\n";

        $ReturnValue .= "</div>\r\n";

        echo($ReturnValue);
    }

    public static function ErrorTypeString($ErrorType)
    {
        $ReturnValue = "";

        switch( $ErrorType )
        {
            default:
                $ReturnValue = "E_UNSPECIFIED_ERROR"; 
                break;
            case E_ERROR: // 1 //
                $ReturnValue = 'E_ERROR'; 
                break;
            case E_WARNING: // 2 //
                $ReturnValue = 'E_WARNING'; 
                break;
            case E_PARSE: // 4 //
                $ReturnValue = 'E_PARSE'; 
                break;
            case E_NOTICE: // 8 //
                $ReturnValue = 'E_NOTICE'; 
                break;
            case E_CORE_ERROR: // 16 //
                $ReturnValue = 'E_CORE_ERROR'; 
                break;
            case E_CORE_WARNING: // 32 //
                $ReturnValue = 'E_CORE_WARNING'; 
                break;
            case E_COMPILE_ERROR: // 64 //
                $ReturnValue = 'E_COMPILE_ERROR'; 
                break;
            case E_CORE_WARNING: // 128 //
                $ReturnValue = 'E_COMPILE_WARNING'; 
                break;
            case E_USER_ERROR: // 256 //
                $ReturnValue = 'E_USER_ERROR'; 
                break;
            case E_USER_WARNING: // 512 //
                $ReturnValue = 'E_USER_WARNING'; 
                break;
            case E_USER_NOTICE: // 1024 //
                $ReturnValue = 'E_USER_NOTICE'; 
                break;
            case E_STRICT: // 2048 //
                $ReturnValue = 'E_STRICT';
                break;
            case E_RECOVERABLE_ERROR: // 4096 //
                $ReturnValue = 'E_RECOVERABLE_ERROR';
                break;
            case E_DEPRECATED: // 8192 //
                $ReturnValue = 'E_DEPRECATED'; 
                break;
            case E_USER_DEPRECATED: // 16384 //
                $ReturnValue = 'E_USER_DEPRECATED'; 
                break;
        }

        return $ReturnValue;
    }
}

$ErrorHandler = new ErrorHandler();

今 - 邪魔にならないコード...

これを実装するには、このファイルをインクルードして「InitializeErrors」メソッドを実行するだけです。これを超えて、エラーをどうしたいかはあなた次第です。これは、PHP が生成する可能性のあるすべてのエラーの単なるラッパーです。特定のエラーの処理方法を変更するには、「AppendError」メソッドでそれを評価し、それに応じて応答するのと同じくらい簡単です。

-- 注意すべきは、説明できない理由で戻り値を実装したことです。その点について自分の作業を確認する必要がありますが、それが結果に影響を与えるかどうかはよくわかりません。

于 2014-12-01T22:23:10.227 に答える
4

必要なエラー ハンドラーには次の 3 種類があります。

  • set_exception_handler、他の方法ではキャッチされない例外をキャッチします。

  • set_error_handler「標準」の PHP エラーをキャッチします。最初にそれをチェックしてerror_reporting、処理または無視する必要があるエラーかどうかを確認し (通常は通知を無視します - おそらく悪いですが、それが私の選択です)、 をスローしErrorExceptionて、例外ハンドラーが出力のためにそれをキャッチできるようにします。

  • register_shutdown_functionと組み合わせるerror_get_last。の値をチェックして['type']、それが であるかどうかE_ERRORE_PARSEまたは基本的にキャッチしたい致命的なエラー タイプであるかどうかを確認します。これらは通常バイパスset_error_handlerするため、ここでキャッチするとつかむことができます。ErrorException繰り返しますが、すべてのエラーが同じ例外ハンドラーによって処理されるように、単に をスローする傾向があります。

これらをどのように実装するかについては、コードの設定方法に完全に依存します。私は通常、ob_end_clean()すべての出力を削除するために を実行し、エラーが報告されたことを知らせる素敵なエラー ページを表示します。

于 2014-12-01T22:37:29.937 に答える