在javascript中抛出用户定义的错误 [英] Throwing user defined error in javascript
本文介绍了在javascript中抛出用户定义的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在javascript中抛出一个异常,我试图在消息中给出异常一个数字,但我只是单独获取消息而不是数字为什么?我究竟做错了什么?
我的代码是:
I am trying to throw an exception in javascript, I am trying to give exception a number along with the message, but i am only getting the message alone and not the number why? what am i doing wrong? my code is:
function ain()
{
var e = new Error("hello guys" ,12345);
throw e;
}
(function() {
try {
ain();
}
catch(e) {
alert(e.number+" "+e.message);
}
}());
输出为:
undefined hello guys
推荐答案
错误
构造函数功能不带数字属性。它只需要一个字符串消息(另外两个参数是非标准的,所以我不会提到它们。)
The Error
constructor function does not take a "number" property. It only takes a string message (the other two parameters are non-standard so I will not mention them).
如果你真的需要使用一个完全自定义的错误对象,你可以抛出一个对象文字而不是一个错误:
If you really need to use a fully customized error object, you can just throw an object literal instead of an error:
try {
throw { message: 'hello world', number: 12345};
} catch(e) {
console.log(e.number + ': ' + e.message);
}
这篇关于在javascript中抛出用户定义的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文