duanbu1421 2010-12-22 14:08
浏览 60

PHP中的错误处理。 怎么做?

I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP.

Look at this function for example:

public function deleteFileFromDisk($fileNameToBeDeleted) {

    $handle = unlink($fileNameToBeDeleted);

    if (!$handle) {
        $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted.";
    } else {
        $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted.";
    }
    return $result;
}

Is this the correct way of doing it, or I can do better than this?

Let me add some details of what I'm achieving...

I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch it and send an e-mail.

Here are the object interactions:

$testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/');
$testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName());
$testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.');
$testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv');               
$testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv');
$testar_classe->deleteDataFromTable('tabela1');
$testar_classe->deleteDataFromTable('tabela2');
$testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1');
$testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2');
$testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName());
$testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv');
$testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); 

Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this?

Best Regards.

  • 写回答

6条回答 默认 最新

  • doudiecai1572 2010-12-22 14:13
    关注

    I'd advice looking into concept of exceptions in PHP. It makes code much clearer and it's more powerful than if..else statements everywhere.

    In your specific case, I'd just throw exception in your function if deleting of file fails and then use it in try..catch statement somewhere else.

    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建