为什么我的 ExpressJS 错误处理程序不起作用?

Jon*_*oep 1 javascript error-handling node.js express

我正在使用 ExpressJS 为我的一个项目构建一个 api,并希望实现错误处理。我在互联网上阅读了一些关于如何执行此操作的文章,并尝试了几种在我的 api 中实现错误处理的方法。我现在遇到的问题是我的错误处理程序不起作用,我不知道为什么。为了让我的问题更清楚,这是我已经尝试过的:

这是我的 index.js 文件的底部:

// Controllers
app.use("/auth", require("./controllers/auth"));
app.use("/clients", require("./controllers/clients"));

// Error handling
app.use((err, req, res, next) => {
    logger.error(
        `date - ${new Date()}, message - ${err.message}, stack trace - ${
            err.stack
        }`
    );

    return res
        .status(500)
        .json({ status: 500, message: "Something went wrong." });
});

const PORT = process.env.PORT || 3001;
app.listen(3001, () => {
    console.log(`Listening on port ${PORT}`);
});
Run Code Online (Sandbox Code Playgroud)

附带说明:我使用 WinstonJS 将错误记录到文件中,并使用 Mongoose 作为 MongoDB 数据库的 ORM。

这是客户端路由的控制器(controllers/clients.js):

const express = require("express");
const router = express.Router();

const ClientsService = require("../services/clients");

// GET -> Get all clients -> /clients
router.get("/", async (req, res) => {
    const clients = await ClientsService.getAll();

    return res.status(200).json({ status: 200, data: clients });
});

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

最后,这是客户端服务(services/clients.js),我想在其中抛出错误(也许这不是抛出错误的正确位置,如果我错了,请纠正我):

const ClientModel = require("../models/Client");

const getAll = async () => {
    return ClientModel.findById({})
        .then(clients => clients)
        .catch(err => {
            throw new Error(err);
        });
};

module.exports = { getAll };
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我在 findById 函数中放置了一个空对象。这是为了强制发生错误,以便我可以测试错误处理。下面几行,我抛出一个错误。我希望这会触发我在 index.js 中定义的中间件函数。该中间件函数(如 index.js 代码所示)将错误记录到文件中,然后向客户端发送 500 响应(读取“用户”)。

相反,我实际上在控制台中收到一个名为“UnhandledPromiseRejectionWarning”的错误。这是错误:

(node:15416) UnhandledPromiseRejectionWarning: Error: CastError: Cast to ObjectId failed for value "{}" at path "_id" for model "clients"
    at D:\projects\myproject\services\clients.js:7:10
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async D:\projects\myproject\controllers\clients.js:8:18
(node:15416) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15416) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise 
rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud)

为什么我的错误处理不起作用?如果您有解决方案,我将如何为我的代码启用错误处理?

先感谢您!

Sul*_*Sah 11

快速错误处理文档中,它说:

您必须捕获路由处理程序或中间件调用的异步代码中发生的错误,并将它们传递给 Express 进行处理。

因此,您需要捕获错误,并使用以下命令将其传递给快速错误中间件next(err)

所以你的控制器需要像这样更新:

router.get("/", async (req, res, next) => {
  try {
    const clients = await ClientsService.getAll();
    return res.status(200).json({ status: 200, data: clients });
  } catch (err) {
    next(err);
  }
});
Run Code Online (Sandbox Code Playgroud)

另外,您最好从您的服务中返回一个承诺,这样更清楚:

const getAll = () => {
  return ClientModel.findById({});
};
Run Code Online (Sandbox Code Playgroud)

现在,如果您担心在每个路线中都使用 try catch,您可以检查答案以避免它。