32

我希望能够捕捉die()exit()消息。这可能吗?我希望有类似于set_error_handlerand的东西set_exception_handler。我看过,register_shutdown_function()但似乎没有包含违规die()exit()呼叫的上下文。

我意识到这一点die()并且exit()是处理错误的坏方法。我不希望被告知不要这样做。:) 我正在创建一个通用系统并希望能够优雅地记录exit()die()如果由于某种原因有人(不是我)认为这是一个好主意。

4

7 回答 7

13

是的,你可以,但你需要ob_startob_get_contentsob_end_cleanregister_shutdown_function

function onDie(){
    $message = ob_get_contents(); // Capture 'Doh'
    ob_end_clean(); // Cleans output buffer
    callWhateverYouWant();
}
register_shutdown_function('onDie');
//...
ob_start(); // You need this to turn on output buffering before using die/exit
@$dumbVar = 1000/0 or die('Doh'); // "@" prevent warning/error from php
//...
ob_end_clean(); // Remember clean your buffer before you need to use echo/print
于 2013-06-04T18:44:07.823 回答
7

根据PHP 手册,在调用 die() 或 exit() 时仍应通知关闭函数。

即使调用了 exit(),也将始终执行关闭函数对象析构函数。

似乎无法获取在 exit($status) 中发送的状态。除非您可以使用输出缓冲来捕获它,但我不确定您如何知道何时调用ob_start().

于 2010-10-01T04:31:02.527 回答
5

如果 APD 可用,override_function()可能 会很有趣

于 2010-10-01T04:46:48.593 回答
4

据我所知,这是不可能的。此处发布的一些解决方案可能有效,但它们需要大量额外工作或许多依赖项。没有办法轻松可靠地捕获 die() 和 exit() 消息。

于 2010-10-18T19:34:31.043 回答
0

为什么不使用自定义错误处理来代替?如果没有,您总是可以使用 LD_PRELOAD 和 C 代码注入来捕获它:) 或者使用您的自定义重新编译 php:P

于 2010-10-01T07:44:48.923 回答
0

如果您使用单点进入方法。(index.php) 我可以推荐这个用于您的错误处理:

简洁版本:

ob_start();
register_shutdown_function('shutdownHandler');

include('something');

define(CLEAN_EXIT, true);

function shutdownHandler() {
    if(!defined("CLEAN_EXIT") || !CLEAN_EXIT) {
        $msg = "Script stopped unexpectedly: ".ob_get_contents();
        //Handle premature die()/exit() here
    }
}

附加步骤和更详细的:

大致是我的做法。我要做的事情比我在这里展示的还要多(处理数据库事务/回滚/发送电子邮件/编写日志/显示友好的错误消息/用户错误报告/等等),但这是所有这些背后的基本思想)。
希望它可以帮助某人。

<?php

    //Some initialization

    //starting output buffering. (fatalErrorHandler is optional, but I recommend using it) 
    ob_start('fatalErrorHandler');

    //Execute code right at the end. Catch exit() and die() here. But also all other terminations inside PHPs control
    register_shutdown_function('shutdownHandler');

    //handling other errors: Also optional
    set_error_handler('errorHandler');



    try {
        //Include of offensive code
        include(...);
    }
    catch (Exception $ex) {
        //Handling exception. Be careful to not raise exceptions here again. As you can end up in a cycle. 
    }

    //Code reached this point, so it was a clean exit.
    define(CLEAN_EXIT, true);


    //Gets called when the script engine shuts down.
    function shutdownHandler() {

        $status = connection_status();

        $statusText = "";

        switch ($status) {
            case 0:
                if (!defined("CLEAN_EXIT") || !CLEAN_EXIT) {
                                    $msg = "Script stopped unexpectedly: ".ob_get_contents();
                    //Handle premature die()/exit() here
                }
                else {
                    //Clean exit. Just return
                    return;
                }
            case 1: $statusText = "ABORTED (1)"; break;
            case 2: $statusText = "TIMEOUT (2)"; break;
            case 3: $statusText = "ABORTED & TIMEOUT (3)"; break;

            default : $statusText = "UNKNOWN ($status)"; break;
        }

        //Handle other exit variants saved in $statusText here ob_get_contents() can have additional useful information here
    }

    // error handler function  (This is optional in your case)
    function errorHandler($errno, $errstr, $errfile, $errline) {

        $msg = "[$errno] $errstr\nOn line $errline in file $errfile";

        switch ($errno) {
            case E_ERROR:               $msg = "[E_ERROR] ".$msg;               break;
            case E_WARNING:             $msg = "[E_WARNING] ".$msg;             break;
            case E_PARSE:               $msg = "[E_PARSE] ".$msg;               break;
            case E_NOTICE:              $msg = "[E_NOTICE] ".$msg;              break;
            case E_CORE_ERROR:          $msg = "[E_CORE_ERROR] ".$msg;          break;
            case E_CORE_WARNING:        $msg = "[E_CORE_WARNING] ".$msg;        break;
            case E_COMPILE_ERROR:       $msg = "[E_COMPILE_ERROR] ".$msg;       break;
            case E_COMPILE_WARNING:     $msg = "[E_COMPILE_WARNING] ".$msg;     break;
            case E_USER_ERROR:          $msg = "[E_USER_ERROR] ".$msg;          break;
            case E_USER_WARNING:        $msg = "[E_USER_WARNING] ".$msg;        break;
            case E_USER_NOTICE:         $msg = "[E_USER_NOTICE] ".$msg;         break;
            case E_STRICT:              $msg = "[E_STRICT] ".$msg;              break;
            case E_RECOVERABLE_ERROR:   $msg = "[E_RECOVERABLE_ERROR] ".$msg;   break;
            case E_DEPRECATED:          $msg = "[E_DEPRECIATED] ".$msg;         break;
            case E_USER_DEPRICIATED:    $msg = "[E_USER_DEPRICIATED] ".$msg;    break;
            default:                    $msg = "[UNKNOWN] ".$msg;               break;
        }

        //Handle Normal error/notice/warning here. 
        $handled = ...

        if ($handled)
            return true; //handled. Proceed execution
        else
            throw Exception($msg); //Be careful. this might quickly become cyclic. Be sure to have code that catches and handles exceptions. Else die() here after logging/reporting the error.

    }

    function fatalErrorHandler(&$buffer) {

        $matches = null;
        //Checking if the output contains a fatal error
        if (preg_match('/<br \/>\s*<b>([^<>].*)error<\/b>:(.*)<br \/>$/', $buffer, $matches) ) {

            $msg = preg_replace('/<.*?>/','',$matches[2]);

            //Handle Fatal error here

            return "There was an unexpected situation that resulted in an error. We have been informed and will look into it."
         }

         //No fatal exception. Return buffer and continue
         return $buffer;
    }
于 2017-12-15T18:37:12.790 回答
-4

是的:编写一个函数并使用它。

function kill($msg){
    // Do your logging..
    exit($msg);
}
于 2010-10-01T05:09:31.557 回答