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.

doushan2224
doushan2224 Andre我的答案代码是由我通过错误处理书籍的粗略研究亲自开发的。我不关心投票。试试我的代码。即使在框架内,我也会完美无缺。
9 年多之前 回复
dongtang1909
dongtang1909 -采取的点。谢谢你的好评。
9 年多之前 回复
drtzb06222
drtzb06222 更简单。这些东西不能互换!错误消息是为了帮助您找到问题。而if(file_exists()是为了避免故意错误。你必须同时使用两者.if(file_exists())unlink());是唯一可能的方式。它不会为缺少的文件设置错误,但是会通知您所有其他错误,例如权限错误
9 年多之前 回复
dongmou5628
dongmou5628 看,你只是把这个操作错误。它不仅可以防止显示错误消息,而且绝对可以消除它!您甚至不会在错误日志中看到它(如您所愿)。所以,id你要防止显示错误-正确使用display_errors=0设置。至于file_exists-这确实很可怕。除了文件之外,错误可能有近千种原因。所以,你马上扔掉它们。并将调试变成噩梦。
9 年多之前 回复
duanhongqiong9460
duanhongqiong9460 在这种情况下更简单。而且我不是说这是应该怎么做的,我只是想向你学习。
9 年多之前 回复
duanmeng3573
duanmeng3573 在代码中的EVERY运算符,或者什么?
9 年多之前 回复
duanpan3166
duanpan3166 它总是很糟糕。压缩错误消息没有一个理由。错误消息是您的朋友。人们应该热衷于看到它们。虽然呕吐他们是自杀。
9 年多之前 回复
doufu5747
doufu5747 我在考虑前端显示代码,而不是OOP。那么@那么糟糕吗?
9 年多之前 回复
doumaogui5937
doumaogui5937 @角色是邪恶的,应该被摧毁!
9 年多之前 回复
douji6667
douji6667 哦,@JMC那将是令人难以置信的愚蠢。
9 年多之前 回复
douhuan1901
douhuan1901 那是臃肿软件,而不是错误处理。为什么不留下它只是取消链接($fileNameToBeDeleted);?你究竟想在这里处理什么?
9 年多之前 回复
doulian8742
doulian8742 PHP错误处理的可能重复
9 年多之前 回复

6个回答



该方法可能会给您带来一些麻烦。 例如,如果您想以编程方式检测函数是否成功,该怎么办? strpos()</ code>表示“错误”或“成功”? 一些替代方案:</ p>


  1. 对于简单的成功/失败案例,返回布尔值true / false。</ li>
  2. 抛出异常 trigger_error( )</ li>
  3. 返回一个特殊的错误容器类,一个la WP_Error ,并检查函数的返回值是否是此类的实例。</ li>
    </ ol>
    </ div>

展开原文

原文

That method would probably create some headaches for you. For example, what if you wanted to programmatically detect if the function had succeeded? strpos() for "Error" or "Success"? Some alternatives:

  1. Return boolean true/false for simple success/failure cases.
  2. Throw exceptions or trigger_error() when something goes wrong.
  3. Return a special error container class, a la WP_Error, and check to see if the return value of the function is an instance of this class.



你在这里做的事情(将一个字符串作为成功/失败指标返回)真是个坏主意。 问题是像这样的字符串只适合呈现给人类; 当它们需要知道是否存在故障时,它们对你的代码绝对无用,如果是,如何处理它。</ p>

阅读这些相关问题:</ p>

展开原文

原文

What you are doing here (returning a string as a success/failure indicator) is really a bad idea. The problem is that strings such as this are only good for presenting to humans; they are absolutely useless to your code when it needs to know if there was a failure and if so, how to handle it.

Read these related questions:

Try looking at exceptions:

public function deleteFileFromDisk($fileNameToBeDeleted) {

    $handle = unlink($fileNameToBeDeleted);

    if (!$handle) {
        throw new Exception("(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted.";
    } 
}

And then in code:

try {
    $object->deleteFileFromDisk('blabla');
}
catch (Exception $e) {
    echo $e->message;
}

In OOP fashion, error handling is mostly done with exceptions. Exceptions should be thrown in exceptional cases, namely when a procedure or routine cannot proceed further if a condition was not met, or if an unexpected scenario has occured.

In your above example, exceptions are not necessary. However, returning a string containing a message that says if it works or not is bad, because it requires the user of the method to parse that string to determine whether or not it worked.

There are two possible outcomes in your method: it worked (true), or it didn't (false). Since your method just deletes a file from disk and do not proceed further, returning a boolean would be just fine.

The routine that uses deleteFromDisk then could throw an exception if the deletion of the file is mandatory in its workflow:

$file = 'foo/bar.txt';
if (!$this->deleteFromDisk($file)) {
   throw new Exception('Directory could not be removed: cannot delete '.$file.' from disk');
}

rmdir('foo/');

In the above example, the deletion of the file is mandatory for the next statement to work, so using exceptions is correct.



我建议研究 PHP中的例外。 它使代码更清晰,并且比任何地方的 if..else </ code>语句更强大。</ p>

在您的特定情况下,我只是在您的函数中抛出异常,如果 删除文件失败,然后在其他地方的 try..catch </ code>语句中使用它。</ p>
</ div>

展开原文

原文

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.

Create sample folder and save my below codes as error.php and create folder error inside sample create empty txt file errorlog.txt

<?php
function error_msg($err_type,$err_msg,$err_file,$err_line)
{
$fh=fopen("error/errorlog.txt","a");
$date1=date("Y-m-d H:i:s");
$er="
===============================================================================================================
"."
Error: Type: ".$err_type."Message: ".$err_msg."ErrorFile: ".$err_file."Errorline: ".$err_line."Time: ".$date1.
"
===============================================================================================================
";
fwrite($fh,$er);
fclose($fh);
}

//set_error_handler("error_msg");
function handler($err_type,$err_msg,$err_file,$err_line)
{
    switch($err_type)
    {
        //fatal error
    case E_ERROR:
        $fh=fopen("error/errorlog.txt","a");
        $date1=date("Y-m-d H:i:s");
        $er="
        ===============================================================================================================
        "."
        Error: Type: ".$err_type."Message: ".$err_msg."ErrorFile: ".$err_file."Errorline: ".$err_line."Time: ".$date1.
        "
        ===============================================================================================================
        ";
        fwrite($fh,$er);
        fclose($fh);
        break;
        //warnings
    case E_WARNING:
        $fh=fopen("error/errorlog.txt","a");
        $date1=date("Y-m-d H:i:s");
        $er="
        ===============================================================================================================
        "."
        Error: Type: ".$err_type."Message: ".$err_msg."ErrorFile: ".$err_file."Errorline: ".$err_line."Time: ".$date1.
        "
        ===============================================================================================================
        ";
        fwrite($fh,$er);
        fclose($fh);
        break;
        //notices
    case E_NOTICE:
        //
        break;

    }
}

set_error_handler("handler");
?>
dtcrw26206
dtcrw26206 另一个膨胀软件的例子。 摆脱这个荒谬的代码。 然后只需设置log_errors和error_log指令。
9 年多之前 回复
doujianwei8217
doujianwei8217 只需使用include“sample / error.php”; 因为函数调用也在我的脚本中,所以只包含它。 我写了两个函数。 使用其中任何一个。
9 年多之前 回复
dongweng6241
dongweng6241 你好,谢谢你的回复。 有一个例子如何使用这两个函数? 最好的祝福。
9 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问