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.

    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?