Error Handling in PHP. How to do it?
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/d开发者_Go百科atabase/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.
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:
- Error handling in PHP
- PHP Error handling
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;
}
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:
- Return boolean true/false for simple success/failure cases.
- Throw exceptions or
trigger_error()
when something goes wrong. - 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.
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.
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");
?>
精彩评论