【问题标题】:how can I handle errors in express globally without using try and catch in my controllers如何在不使用控制器中的 try 和 catch 的情况下全局处理 express 中的错误
【发布时间】:2020-09-07 10:15:26
【问题描述】:

我对表达很陌生,想知道是否存在全局错误捕获器。我正在处理一个已经创建的所有控制器的现有代码,在所有控制器中实现 try 和 catch 将是新手。我需要一个全局错误捕获器来检测代码中的中断并响应客户端。是否有现有的库或现有的代码实现。

【问题讨论】:

标签: node.js express


【解决方案1】:

如果您的控制器不是异步的,您可以简单地添加错误处理程序之后您注册了所有路由

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    throw new Error('Something went wrong');
});

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from non-async route above will be handled here
    res.status(500).send(err.message)
});

app.listen(port);

如果您的控制器是异步的,您需要在控制器中添加自定义中间件来处理异步错误。中间件示例取自this answer

const express = require('express');
const app = express();
const port = 3000;

// Error handler middleware for async controller
const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

app.get('/', asyncHandler(async (req, res) => {
    throw new Error("Something went wrong!");
}));

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from async & non-async route above will be handled here
    res.status(500).send(err.message)
})

app.listen(port);

【讨论】:

    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2023-03-03
    • 2019-05-26
    • 2016-06-16
    相关资源
    最近更新 更多