javascript - 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);
}
解决方案
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
}
推荐阅读
- python - 如何输入包含哈希值的字符串,并将其与 hashlib 方法一起使用
- typescript - 表单验证错误消息未以角度 8 的反应形式显示
- php - PHP 登录页面出现 11 个错误
- python - 未定义全局名称“RomanNumeralConverter”
- python - 如何使用 ssh 隧道访问 django multi-tanant 应用程序的子域?
- .net - 为什么我不能在课堂上使用 Viebag
- navigation - 如何在 SwiftUI 中将 NavigationLink 显示为按钮
- ios - 在 tableview 单元格中显示旧图像
- java - 从适配器(asyncTask)更新片段的文本视图
- python - 我已将我的应用程序捆绑在 .exe 中,但它无法找到其他工作文件