如何可靠地识别PHP中的特定错误? [英] How can I reliably identify a specific error in PHP?

查看:119
本文介绍了如何可靠地识别PHP中的特定错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于PHP的 unlink()本身不支持异常,我正在为其创建一个包装函数。它应该抛出一个 FileNotFoundException ,如果,那么给定的文件不能被删除,因为它不存在。

Because of PHP's unlink() not supporting exceptions natively, I'm making a wrapper function for it. It should throw a FileNotFoundException if, well, the given file could not be deleted because it doesn't exist.

为此,我需要确定由 unlink()抛出的错误是由缺少的文件或其他内容引起的。

For this, I need to determine whether the error thrown by unlink() was caused by a missing file or something else.

这是我自定义删除功能的测试版本:

This is my test version for a custom delete function:

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):没有这样的文件或目录

For $errLevel and $errString I get 2 (E_WARNING) and unlink(/tmp/fooNonExisting): No such file or directory

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

A rather bold approach would be like this:

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

问题1:我可以依赖于不同PHP版本的错误字符串相同吗?问题2:有更好的方法吗?

Question 1: How much can I rely on the error string being the same across different PHP versions? Question 2: Is there a much better way?

推荐答案

我将简化代码:

public function deleteFile($path){

    if (!file_exists($path) {
        throw new FileNotFoundException();
    }else{
        unlink($path);
    }

    if (file_exists($path) {
        throw new FileNotDeleted();
    }
}

然后你没有抓住 $ errstr 并执行复杂的错误捕获,当引入异常时,它将适用于PHP 4。

Then you don't have to catch the $errstr and do complicated error catching. And it will work down to PHP 4 when exceptions were introduced.

这篇关于如何可靠地识别PHP中的特定错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆