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

标签 php exception

由于 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) 和 unlink(/tmp/fooNonExisting): No such文件或目录

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

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。

关于php - 如何可靠地识别 PHP 中的特定错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899863/

相关文章:

java - JTA事务意外回滚,嵌套异常为javax.transaction.RollbackException

php - 拉维尔 5 : app() helper function

php - 如何在laravel 5.5的s3存储桶中上传图像

C#/PHP : Is there an equivalent of PHP's array_map() function in C#?

Kotlin:尝试,捕捉,并且只有在最后出现错误时

c++ - 在分配 scoped_ptr 之前处理异常

c# - Entity Framework v5 候选版本在模型中使用枚举时抛出异常

c# - 如何在 C# 中创建自定义异常

php - 自定义数据库驱动博客上的分页?

php - PHP 中的 "Webpage has expired"$_SESSIONS