首页 > 解决方案 > Javascript 控制台记录扩展异常

问题描述

有些库会引发扩展错误,例如 GraphQl Apollo 给出了一个。尝试将其直接记录到控制台中只会给出隐藏详细信息的“服务器错误”之类的一般标题。

有没有办法像其他对象一样将错误对象打印到控制台中,让您浏览它?以下代码是问题代码的再现。

class RError extends Error {
    constructor({name, message, cause}) {
        super();
        this.name = name;
        this.message = message;
        this.cause = cause;
    }
}

function fail() {
    throw new RError({
        name: 'BAR',
        message: 'I messed up.'
    });
}

function failFurther() {
    try {
        fail();
    } catch (err) {
        throw new RError({
            name: 'FOO',
            message: 'Something went wrong.',
            cause: err
        });
    }
}

try {
    failFurther();
} catch (err) {
    // Prints "FOO: Something went wrong" and stacktrace, hiding the cause
    console.error(err);
    // It's still available if you know the path
    console.error(err.cause);
}

标签: javascriptexceptionconsole

解决方案


console.error()基本上是为了显示错误信息。如果想要其他一切,只需使用其他方法.log(), .dir(), .table()...

class RError extends Error {
    constructor({name, message, cause}) {
        super();
        this.name = name;
        this.message = message;
        this.cause = cause;
    }
}

function fail() {
    throw new RError({
        name: 'BAR',
        message: 'I messed up.'
    });
}

function failFurther() {
    try {
        fail();
    } catch (err) {
        throw new RError({
            name: 'FOO',
            message: 'Something went wrong.',
            cause: err
        });
    }
}

try {
    failFurther();
} catch (err) {
    console.log(err);
    console.dir(err);
    console.table(err); // Not implemented in Stack Overflow snippets
}


推荐阅读