5

ファイルシステム関数を使用する場合、次のようなエラーを処理する正しい方法は何でしょうか。

警告: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']}";
}
4

2 に答える 2

4

例外をスローするエラーハンドラーを設定したいと思います。

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    // see http://php.net/manual/en/class.errorexception.php
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

set_error_handler("exception_error_handler");

その場合、コードは次のようになります。

try {
    symlink(); // when an error occured, it jumps to the catch
} catch (ErrorException $ex) {
    // do stuff with $ex
}
于 2012-11-13T18:25:01.830 に答える
1

ファイルシステム操作に広く使用され、テストされているソリューションであるFileysystemコンポーネントを使用することをお勧めしますhttps://github.com/symfony/Filesystem/blob/master/Filesystem.php#L248

于 2012-11-13T18:29:53.257 に答える