Home > Blockchain >  Express: new Error() is not working outside of server.js/index.js
Express: new Error() is not working outside of server.js/index.js

Time:07-19

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:

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. 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:

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.

Appreciate any feedback on the questions, or any ideas on where I did something wrong

CodePudding user response:

The code you show in your sandbox is doing this 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. 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. They are merely functions. Therefore, they can't be called with 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);
  }
});
  • Related