简体   繁体   English

Express: new Error() 在 server.js/index.js 之外不起作用

[英]Express: new Error() is not working outside of server.js/index.js

I created a simple custom exception based on this link as follows:我基于此链接创建了一个简单的自定义异常,如下所示:

function userErr(message) {
  logger.info("reach user error function")
  const error = new Error(message);
  error.type = "userErr";
  return error;
}

function failureErr(message) {
  logger.info("reach failure error function")
  const error = new Error(message);
  error.type = "failureErr";
  return error;
}

The expected behaviour is Express will throw this error to the custom error handler middleware at the end of the server.js file:预期的行为是 Express 会在 server.js 文件末尾向自定义错误处理程序中间件抛出此错误:

app.use((error, req, res, next) => {
  console.log("Error Handling Middleware: " + error.message);

  if (error.type === "userErr") {
    res.status(400).json({
      status: "error",
      statusCode: "400",
      message: error.message
    });
  } else if (error.type === "failureErr") {
    res.status(500).json({
      status: "fail",
      statusCode: "500",
      message: error.message
    });
  } else {
    res.status(500).json({
      status: "error",
      statusCode: "500",
      message: error.message
    });
  }
});

app.listen(8080, () => {
  console.log("listening on 8080...");
}); //the server object listens on port 8080

When I put these functions above the routes (app.get, app.post, etc...) in the server.js file (this should be index.js for most people), it works fine.当我将这些函数放在 server.js 文件(对于大多数人来说应该是 index.js)中的路由(app.get、app.post 等)之上时,它工作正常。 But when I start stripping out these routes and put them into a route file in the routes folder instead, the traffic does come to the route correctly, but whenever an error occurs and executes the function above, JavaScript threw an error at the 2nd line, which is:但是当我开始剥离这些路由并将它们放入路由文件夹中的路由文件时,流量确实正确地到达了路由,但是每当发生错误并执行上面的函数时,JavaScript 在第二行抛出错误,这是:

const error = new Error(message);

for example:例如:

const error = new Error(message);
                ^

Error: [object Object]
    at new failureErr (file:///.../src/server.js:89:17)
    at file:///.../src/routes/testRoutes.js:104:21 {
  type: 'failureErr'

Which is weird!这很奇怪! I have tried putting these functions into a separate file and importing them into the route file, but it still shows the same error.我尝试将这些函数放入单独的文件中并将它们导入到路由文件中,但它仍然显示相同的错误。

I mimicked the folder into the codesandbox (I couldn't manage to make it run) so you can understand the context.我将文件夹模仿到代码沙箱中(我无法让它运行),以便您了解上下文。 The index.js by itself is the one that works, while index2.js with the routers folder is the one that failed. index.js 本身是有效的,而带有 routers 文件夹的 index2.js 是失败的。

Appreciate any feedback on the questions, or any ideas on where I did something wrong感谢对问题的任何反馈,或对我做错了什么的任何想法

The code you show in your sandbox is doing this throw new userError("It's an user error");您在沙箱中显示的代码正在执行此throw new userError("It's an user error"); , but userError() is not properly set up as a constructor and thus can't be called with new . ,但userError()未正确设置为构造函数,因此无法使用new调用。 This is the code in your sandbox:这是沙箱中的代码:

app.get("/api/v1/test", (req, res, next) => {
  try {
    const userErr = req.headers.userErr;
    console.log(userErr);
    if (userErr === "true") {
      throw new userError("It's an user error");
    } else {
      throw new failureError("It's an failure error");
    }
  } catch (e) {
    next(e);
  }
});

The code you show has not made either userError() or failureError() into classes or constructors.您显示的代码没有将userError()failureError()放入类或构造函数中。 They are merely functions.它们只是功能。 Therefore, they can't be called with new .因此,它们不能用new调用。

If you want to make them into classes, then do something like this:如果您想将它们变成类,请执行以下操作:

class userError extends Error {
    constructor(message) {
        super(message);
        console.log("reach user error function");
        this.type = "userErr";
    }
}

Note, this is the more modern way of doing this than what is shown in the article you reference (which is apparently old).请注意,这是比您引用的文章(显然是旧的)中显示的更现代的方法。

Or, you can just use what you have as functions:或者,您可以只使用您拥有的功能:

app.get("/api/v1/test", (req, res, next) => {
  try {
    const userErr = req.headers.userErr;
    console.log(userErr);
    if (userErr === "true") {
      next(userError("It's an user error"));
      return;
    } else {
      next(failureError("It's an failure error"));
      return;
    }
    res.send("ok");
  } catch (e) {
    next(e);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM