JavaScript では、エラーをスローする 2 つの方法に気付きました。
1)
throw "An error";
2)
throw new Error('An object error')
他の方法よりも 1 つの方法を選択する利点はありますか? より良い慣行と見なされますか?
ありがとう
JavaScript では、エラーをスローする 2 つの方法に気付きました。
1)
throw "An error";
2)
throw new Error('An object error')
他の方法よりも 1 つの方法を選択する利点はありますか? より良い慣行と見なされますか?
ありがとう
Basically, JavaScript is implicitly throwing an Error object with "An error" as the message when you use method one. Unless you need to throw a different kind of exception (for example, one that has different properties explaining the error) method one is fine.
However, if you plan on throwing more complex exceptions in the future, you'll need to use method 2, as you'll need to define which object you're throwing.
Basically, for this purpose both are equivalent. I'd go with method 2, since it will put you in the right mindset down the road ;)
Error
オブジェクトには、 and (Firefoxの場合)のような素敵な追加機能があります。error.name
error.stack
それらが必要な場合は、明示的にエラーをスローしてください。ただし、ほとんどの人はerror.toString()
メソッドを使用するだけです (多くの場合、暗黙的に呼び出されます)。後者の場合、そもそも Error オブジェクトを作成するのはやり過ぎなので、文字列をスローしても同様に機能します。