如何可靠地识别 PHP 中的特定错误


How can I reliably identify a specific error in PHP?

由于PHP的unlink()本身不支持异常,我正在为它制作一个包装器函数。如果给定的文件因为不存在而无法删除,它应该抛出FileNotFoundException

为此,我需要确定unlink()抛出的错误是由丢失的文件还是其他原因引起的。

这是我自定义删除函数的测试版本:

public function deleteFile($path){
    set_error_handler(function($errLevel, $errString){
        debug($errLevel);
        debug($errString);
    });
    unlink($path);
    restore_error_handler();
}

对于$errLevel$errString,我得到2 (E_WARNING)和取消链接(/tmp/fooNonExisting):没有这样的文件或目录

一个相当大胆的方法应该是这样的:

if( strpos($errString, 'No such file or directory') !== false ) {
    throw new FileNotFoundException();
};

问题 1:我可以在多大程度上依赖不同 PHP 版本中相同的错误字符串?问题2:有没有更好的方法?

我会简化代码:

public function deleteFile($path){
    if (!file_exists($path) {
        throw new FileNotFoundException();
    }else{
        unlink($path);
    }
    if (file_exists($path) {
        throw new FileNotDeleted();
    }
}

这样,您就不必捕获$errstr并进行复杂的错误捕获。当引入异常时,它将工作到 PHP 4。

在阅读我的旧问题时,我遇到了ErrorException,结合set_error_handler()这将是所有本机PHP错误的自动错误到异常转换器

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
unlink('Does not exitsts'); 

谁能教授这个?

我相信

它(即您的代码)应该足够可移植......至于实现相同目标的更好方法,我会以不同的方式做事(虽然代码很简单,但它也更具可读性......所以请耐心等待)

function deleteFile($file_path){
    if(!is_file($file_path)){
        throw new Exception("The path does not seem to point to a valid file");
    }
    if(!file_exists($file_path)){
        throw new Exception("File not found!");
    }
    if(unlink($file_path)){
        return true;
    } else {
        throw new Exception("File deletion failed!");
    }
}

当然,您可以随时压缩和改进代码...跳这个帮助!

多年来,

我看到 php 错误消息发生了很大变化。也许,尝试在一段非常精细的代码中检测上一个错误中的更改,然后在非常松散的庄园中导致字符串解析。

$lastErr = error_get_last();
unlink($file);
if ($lastErr !== error_get_last()) {
    // do something
    //maybe string parsing and/or testing with file_exists, is_writable etc...
}