Because of PHP's unlink()
not supporting exceptions natively, I'm making a wrapper function for it. It should throw a FileNotFoundException
if, well, the given file could not be deleted because it doesn't exist.
For this, I need to determine whether the error thrown by unlink()
was caused by a missing file or something else.
This is my test version for a custom delete function:
public function deleteFile($path){
set_error_handler(function($errLevel, $errString){
debug($errLevel);
debug($errString);
});
unlink($path);
restore_error_handler();
}
For $errLevel
and $errString
I get 2 (E_WARNING) and unlink(/tmp/fooNonExisting): No such file or directory
A rather bold approach would be like this:
if( strpos($errString, 'No such file or directory') !== false ) {
throw new FileNotFoundException();
};
Question 1: How much can I rely on the error string being the same across different PHP versions? Question 2: Is there a much better way?