使用文件系统函数时,处理错误的正确方法是什么,例如:
警告:symlink():在第 XXX 行的 /path-to-script/symlink.php 中没有这样的文件或目录
我通常的方法是在调用文件系统函数之前检查任何可能产生错误的条件。但是,如果命令由于我没有预见到的原因而失败,我如何捕捉错误以向用户显示更有用的消息?
这是创建符号链接的代码的简化:
$filename = 'some-file.ext';
$source_path = '/full/path/to/source/dir/';
$dest_path = '/full/path/to/destination/dir/';
if(file_exists($source_path . $filename)) {
if(is_dir($dest_path)) {
if( ! file_exists($dest_path . $filename)) {
if (symlink($source_path . $filename, $dest_path . $filename)) {
echo 'Success';
} else {
echo 'Error';
}
}
else {
if (is_link($dest_path . $filename)) {
$current_source_path = readlink($dest_path . $filename);
if ( $current_source_path == $source_path . $filename) {
echo 'Link exists';
} else {
echo "Link exists but points to: {$current_source_path}";
}
} else {
echo "{$source_path}{$filename} exists but it is not a link";
}
}
} else {
echo "{$source_path} is not a dir or doesn't exist";
}
} else {
echo "{$source_path}{$filename} doesn't exist";
}
跟进/解决方案
正如 Sander 所建议的那样,set_error_handler()
用于将错误和警告转换为异常。
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
symlink($source_path . $filename, $dest_path . $filename);
echo 'Success';
}
catch (ErrorException $ex) {
echo "There was an error linking {$source_path}{$filename} to {$dest_path}{$filename}: {$ex->getMessage()}";
}
restore_error_handler();
使用 @ 运算符是另一种解决方案(尽管有些人建议尽可能避免使用它):
if (@symlink($source_path . $filename, $dest_path . $filename)) {
echo 'Success';
} else {
$symlink_error = error_get_last();
echo "There was an error linking {$source_path}{$filename} to {$dest_path}{$filename}: {$symlink_error['message']}";
}