サーチ…


前書き

Errorオブジェクトを作成する方法と、Node.jsでエラーをスロー&処理する方法を学びます

エラー処理のベストプラクティスに関連する将来の編集。

エラーオブジェクトの作成

新しいエラー(メッセージ)

messageが作成されたオブジェクトのmessageプロパティに設定されている新しいエラーオブジェクトを作成します。通常、 message引数はErrorコンストラクタに文字列として渡されます。しかし、 message引数が文字列ではないオブジェクトの場合、Errorコンストラクタは渡されたオブジェクトの.toString()メソッドを呼び出し、その値を作成されたエラーオブジェクトのmessageプロパティに設定します。

var err = new Error("The error message");
console.log(err.message); //prints: The error message
console.log(err);
//output
//Error: The error message
//    at ... 

各エラーオブジェクトにはスタックトレースがあります。スタックトレースには、エラーメッセージの情報が含まれ、エラーが発生した場所が示されます(上記の出力にはエラースタックが表示されます)。エラーオブジェクトが作成されると、システムは現在の行のエラーのスタックトレースを取得します。スタックトレースを取得するには、作成されたエラーオブジェクトのスタックプロパティを使用します。下の2行は同じです:

console.log(err);
console.log(err.stack);

投げるエラー

例外が処理されず、ノード・サーバーがクラッシュする場合、投げ込みエラーは例外を意味します。

次の行はエラーをスローします:

throw new Error("Some error occurred"); 

または

var err = new Error("Some error occurred");
throw err;

または

throw "Some error occurred";

最後の例(文字列を投げる)は良い方法ではなく、推奨されません(常にErrorオブジェクトのインスタンスであるエラーを投げる)。

あなたがあなたの中にエラーをthrowた場合、システムはその行でクラッシュします(例外ハンドラがない場合)、その行の後にコードは実行されません。

var a = 5;
var err = new Error("Some error message");
throw err; //this will print the error stack and node server will stop
a++; //this line will never be executed
console.log(a); //and this one also

しかし、この例では:

var a = 5;
var err = new Error("Some error message");
console.log(err); //this will print the error stack
a++; 
console.log(a); //this line will be executed and will print 6

try ... catchブロック

try ... catchブロックは例外を処理するためのもので、例外はエラーではなくスローされたエラーを意味します。

try {
    var a = 1;
    b++; //this will cause an error because be is undefined
    console.log(b); //this line will not be executed
} catch (error) {
    console.log(error); //here we handle the error caused in the try block
}

tryブロックb++エラーが発生し、そのエラーがcatchブロックに渡されますcatchブロックには、catchブロックで同じエラーがスローされたり、スローされたり、スローされたりすることがあります。次の例を見てみましょう。

try {
    var a = 1;
    b++;
    console.log(b);
} catch (error) {
    error.message = "b variable is undefined, so the undefined can't be incremented"
    throw error;
}

上記の例では、 errorオブジェクトのmessageプロパティを変更し、変更されたerrorスローしerror

tryブロックのエラーをすべて調べ、catchブロックで処理できます。

try {
    var a = 1;
    throw new Error("Some error message");
    console.log(a); //this line will not be executed;
} catch (error) {
    console.log(error); //will be the above thrown error 
}


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow