如何在node.js中使用Error.captureStackTrace

Shi*_*aay 11 node.js

最近我正在研究 Node.js 中全局错误处理中间件的实现。然后,我遇到了这个Error.captureStackTrace(this,this.constructor)。

我检查了 Node 文档并发现 - 在 targetObject 上创建一个 .stack 属性,该属性在访问时返回一个字符串,表示调用 Error.captureStackTrace() 的代码中的位置。

MDN 文档 - 维护正确的堆栈跟踪以查找抛出错误的位置

appError.js 文件

class AppError extends Error {
constructor(message, statusCode) {
super(message);

this.statusCode = statusCode;

 // Error.captureStackTrace(this, this.constructor);
}}
Run Code Online (Sandbox Code Playgroud)

app.js 文件

const AppError = require('./appError');
const express = require('express');
const app = express();

app.all('*', (req,res,next) => {
         const custErr = new AppError('Mentioned Route is not available on server','404');
         next();
})
Run Code Online (Sandbox Code Playgroud)

当我尝试调试代码时我的观察:

  1. 我发现 .stack 属性在 custErr 对象上可用,即使我在 appError.js 文件中注释了 Error.captureStackTrace(this, this.constructor) 。
  2. 我仍然很困惑如何利用 Error.captureStackTrace()

有人可以解释一下吗?

eol*_*eol 8

您需要了解的一件事是,除了类的实例之外,Error语句throw还可以抛出其他类型。例如考虑这个:

function throwSomeObj() {
    throw {statusCode: 500};
}

try {
  throwSomeObj();
} catch(err) {
  console.log(err);
  console.log(err.stack);
}
Run Code Online (Sandbox Code Playgroud)

抛出的异常会产生您传递给它的对象,即{statusCode: 500}. 现在,正如您所看到的,该对象没有任何堆栈跟踪,因为undefined已记录。

但是,您可以用来Error.captureStackTrace捕获抛出错误的堆栈跟踪。考虑一下:

function throwObjWithStacktrace() {
    const someError = {statusCode: 500}
    Error.captureStackTrace(someError)
    throw someError;
}


try {
    throwObjWithStacktrace();
} catch (err) {
    console.log(err);
    console.log(err.stack);
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,现在err包含 stack 属性并包含引发错误的函数的堆栈。

请注意,实例化新Error对象时,堆栈将自动设置在该对象上。