gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:58:06 28 4
gpt4 key购买 nike

最近我正在研究 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);
}}
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();
})
我尝试调试代码时的观察结果:
  • 我发现 .stack 属性在 custErr 对象上可用,即使我已经评论了
    appError.js 文件中的 Error.captureStackTrace(this, this.constructor)。
  • 我仍然很困惑如何利用 Error.captureStackTrace()

  • 有人可以解释我吗?

    最佳答案

    您需要了解的一件事是,除了 Error 的实例之外- 类 throw -语句也可以抛出other types .考虑这个例如:

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

    try {
    throwSomeObj();
    } catch(err) {
    console.log(err);
    console.log(err.stack);
    }

    抛出的异常产生你传递给它的对象,即 {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);
    }

    如您所见,现在 err包含 stack 属性并包含到抛出错误的函数的堆栈。
    注意在实例化一个新的 Error 时-object 堆栈将自动设置在该对象上。

    关于node.js - 如何在 node.js 中使用 Error.captureStackTrace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63598211/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com