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

发布于 2024-10-09 06:13:06 字数 1588 浏览 0 评论 0原文

我是 PHP OOP 的初学者,我对 PHP 中处理错误的正确方法有些怀疑。

例如,看看这个函数:

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;
}

这是正确的方法吗,还是我可以做得更好?

让我添加一些我所实现的细节......

我正在运行类方法,并且我需要控制过程中的错误。如果对该对象的任何调用引发错误,我需要捕获它并发送电子邮件。

以下是对象交互:

$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'); 

哪种是处理此问题的最佳方法?创建一个新方法来处理异常?有关于如何执行此操作的示例吗?

此致。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

七七 2024-10-16 06:13:06

你在这里所做的(返回一个字符串作为成功/失败指示器)确实是一个坏主意。问题是这样的字符串只适合呈现给人类;当您的代码需要知道是否发生故障以及如果是的话,如何处理它时,它们对您的代码绝对没有用处。

阅读这些相关问题:

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:

软糯酥胸 2024-10-16 06:13:06

尝试查看 异常

public function deleteFileFromDisk($fileNameToBeDeleted) {

    $handle = unlink($fileNameToBeDeleted);

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

然后在代码中:

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

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;
}
一百个冬季 2024-10-16 06:13:06

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

  1. 对于简单的成功/失败情况,返回布尔值 true/false。
  2. 抛出异常trigger_error() 当出现问题时。
  3. 返回一个特殊的错误容器类,例如 WP_Error,并检查返回值是否为该函数是此类的一个实例。

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.
薄荷梦 2024-10-16 06:13:06

在 OOP 方式中,错误处理主要是通过异常完成的。在异常情况下,即当不满足条件或发生意外情况而过程或例程无法进一步进行时,应抛出异常。

在上面的例子中,例外是不必要的。但是,返回一个包含说明该方法是否有效的消息的字符串是不好的,因为它需要该方法的用户解析该字符串以确定它是否有效。

您的方法有两种可能的结果:有效(正确),或无效(错误)。由于您的方法只是从磁盘中删除文件并且不再继续,因此返回布尔值就可以了。

如果在其工作流程中强制删除文件,则使用 deleteFromDisk 的例程可能会引发异常:

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

rmdir('foo/');

在上面的示例中,必须删除文件才能使下一条语句起作用,因此使用例外是正确的。

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.

池木 2024-10-16 06:13:06

我建议研究PHP 中的异常的概念。它使代码更加清晰,并且比任何地方的 if..else 语句更强大。

在您的具体情况下,如果删除文件失败,我只会在您的函数中抛出异常,然后在其他地方的 try..catch 语句中使用它。

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.

白首有我共你 2024-10-16 06:13:06

创建 sample 文件夹并将以下代码保存为 error.php 并在示例中创建文件夹 error 创建空 txt 文件 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");
?>

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");
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文