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);
}