以防万一有人在多年后仍然像我现在一样在寻找,我想指出,Pointy 的(正确)答案是引导我找到问题答案的原因:我可以扔一个自定义“警告”对象?
Pointy 指出,“你几乎可以扔任何东西”,这让我找到了 throw 的文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
摘录:
// Syntax
throw expression; // expression to throw
// Examples
throw 'Error2'; // generates an exception with a string value
throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true
throw new Error('Required'); // generates an error object with the message of Required
// Throw an object - you can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.
// Example
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
function getMonthName(mo) {
mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException('InvalidMonthNo');
}
}
try {
// statements to try
var myMonth = 15; // 15 is out of bound to raise the exception
var monthName = getMonthName(myMonth);
} catch (e) {
monthName = 'unknown';
console.log(e.message, e.name); // pass exception object to err handler
}
Pointy 给出了(未确认的)正确答案,我只是在补充文档和示例
附:抱歉,Pointy,我什至没有足够的声望来支持你(13/15):-(