本页概述了如何在Javascript中创建自定义异常:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw.
但是,自定义异常没有打印预期的输出。所需输出仅在调用console.log(e.toString())
时发生,但目标是使用console.log(e)
查看所需输出。
console.log(e)
:的期望输出
500: Unexpected error
console.log(e)
:的实际输出
{
statusCode: 500,
statusMessage: "Unexpected error",
toString: function () {
return this.statusCode + ': ' + this.statusMessage;
}
}
代码
function TestException(statusCode, statusMessage) {
this.statusCode = statusCode;
this.statusMessage = statusMessage;
this.toString = function() {
return this.statusCode + ': ' + this.statusMessage;
};
}
try {
throw new TestException(500, 'Unexpected error');
} catch (e) {
console.log(e);
}
您必须有一个异常来帮助您:
const TestException = (statusCode, statusMessage) => {
this.statusCode = statusCode;
this.statusMessage = statusMessage;
this.toString = () => {
return this.statusCode + ': ' + this.statusMessage;
}
if(!isNaN(this.statusCode) || this.statusMessage !== null) {
throw this.toString();
}
}
try {
throw TestException("500", 'Unexpected error');
} catch (e) {
console.log(e);
}