記錄致命錯誤

在 PHP 中,致命錯誤是一種無法捕獲的錯誤,即在遇到致命錯誤後程式無法恢復。但是,要記錄此錯誤或以某種方式處理崩潰,你可以使用 register_shutdown_function 註冊關閉處理程式。

function fatalErrorHandler() {
    // Let's get last error that was fatal.
    $error = error_get_last();
   
    // This is error-only handler for example purposes; no error means that
    // there were no error and shutdown was proper. Also ensure it will handle 
    // only fatal errors.
    if (null === $error || E_ERROR != $error['type']) {
        return;
    }

    // Log last error to a log file.
    // let's naively assume that logs are in the folder inside the app folder.
    $logFile = fopen("./app/logs/error.log", "a+");

    // Get useful info out of error.
    $type    = $error["type"];
    $file    = $error["file"];
    $line    = $error["line"];
    $message = $error["message"]

    fprintf(
        $logFile,
        "[%s] %s: %s in %s:%d
",
        date("Y-m-d H:i:s"),
        $type,        
        $message,
        $file, 
        $line);

    fclose($logFile);       
}

register_shutdown_function('fatalErrorHandler');

參考: