【问题标题】:Javascript: toString function for custom exception not displaying expected outputJavascript:自定义异常的 toString 函数不显示预期输出
【发布时间】:2021-05-26 20:43:17
【问题描述】:

本页概述了如何在 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);
}

【问题讨论】:

    标签: javascript exception javascript-objects


    【解决方案1】:

    你必须有一个例外来帮助你:

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

    【讨论】:

    • 谢谢,但这不会更新 statusCodestatusMessage 属性?
    • 是的,对不起?,但是如果你插入一个异常,你必须解决问题
    猜你喜欢
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2013-08-02
    • 2020-03-15
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多