0

ファイルが正しければうまく機能しますが、エラーを正しく処理できません。

function parse (pathname, callback){
    //Some variables

    fs.open(pathname, 'r', function(err, fd){
        if (err){console.log('Error Opening the file'); callback(-1);}
        console.log('Begin the parsing');
        //Do the parsing

しかし、無効なパス名を指定すると、Error のメッセージが表示され、関数は読み取り時に致命的なエラーが発生するまで続行されます。

コールバックが関数を終了していると思っていましたが、間違っているようです。

私は次のようなことができます:

function parse (pathname, callback){
    //Some variables

    fs.open(pathname, 'r', function(err, fd){
        if (err){console.log('Error Opening the file'); callback(-1);}
        else{
            console.log('Begin the parsing');
            //Do the parsing

しかし、その中には多くのエラー処理があり、関数は非常に巨大です。

他のsコードでは、私は通常見ます

if (err){throw err;}

しかし、イベントを使って簡単なことをしてもうまくいかないので、これも避けたいと思います。それを処理しないと、アプリが閉じてしまいます。

別の方法でエラーを処理できるようにする適切な方法はありますか?

4

1 に答える 1

1

parse関数の実行を中断する関数を返すことができます。

if (err) {
    console.log('Error opening the file');
    callback(-1);
    return; // Alternatively return false or anything you want
}

他の関数callback(-1)と同じように単純な関数呼び出しであるため、関数を呼び出しても関数は終了しません。console.log()

于 2013-09-10T12:55:37.847 に答える