如何解决Javascript:自定义异常的 toString 函数不显示预期输出
此页面概述了如何在 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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。