PHP——使用debug_backtrace的结果来显示不同的错误消息是个好主意吗?


PHP - is it a good idea to use the results of debug_backtrace to display different error messages?

在我的PHP应用程序中有几个地方,根据之前调用的函数,如果出现问题,我需要显示不同的错误消息。

例如,在下面的例子中,如果你直接在一个'file'上调用startEdit()函数,并且该文件被锁定,它应该返回一个特定的错误消息。但是,如果startEdit()函数是作为父文件夹中的startEdit()函数的结果被调用的,它应该显示一个不同的错误信息(见下面的例子):

<?php
    class folder{
        public $files = array();
        public function startEdit(){
            //when we start editing a folder, start editing all files within it
            foreach($this->files as $file){
                $file->startEdit();
            }
        }
    }
    class file{
        public $isLocked = true;
        public function startEdit(){
            try{
                //if the file is locked we need to throw an exception
                if($this->isLocked==1){
                    //loop through the stack trace to see if this was called from the folder class.
                    foreach(debug_backtrace() as $frame){
                        if($frame['class']=='folder'){
                            throw new Exception("Cannot edit this folder because one of the files within it are locked");
                        }
                    }
                    //if not called from the folder class then throw a different error
                    throw new Exception("This file is locked");
                }
            }catch(Exception $e){
                exit("Exception: ".$e->getMessage());
            }
        }
    }
    //create a new folder
    $folder = new folder();
    //put some files within it
    $file1 = new file();
    $file2 = new file();
    $folder->files = array($file1, $file2);
    //start editing the folder - should return the message 'Cannot edit this folder because one of the files within it are locked'
    $folder->startEdit();
    //try editing one of the files - should return the message 'This file is locked'
    $file1->startEdit();
?>

这是我试图做的一个非常简化的版本-在我的应用程序中,错误消息可能依赖于5或6个堆栈帧前调用的函数。

我的问题是——这是一种有效的做事方式吗?有没有更好的方法来实现这个目标?

谢谢!

更新

只是为了清楚,我不想向用户显示实际的堆栈跟踪,我想使用堆栈跟踪为用户创建更多有用的消息。我想另一种方法是给每个函数传递另一个参数告诉它它是从哪里被调用的?

有其他人尝试过做类似的事情吗?任何帮助,这将是非常感激!

最后我决定不使用debug_backtrace()。这是因为它返回的数组可能非常大(取决于函数调用的次数),所以我认为它可能会影响性能。在上面的例子中,我将在'file'对象上实现一个名为canStartEdit()的方法,并在'folder'对象中调用它——这样我就可以在folder对象中抛出一个异常,而不必在file对象中执行,然后计算出之前发生了什么。

有一个在docs

中提到的$limit选项

debug_backtrace