express.js global try/catch

Asa*_*evo 5 javascript node.js express

我正在使用Express在Node JS上开发一个休息服务器.

我正在尝试将所有端点包装在try\catch块中,因此错误的中心点将通过详细信息响应发送方.我的问题是响应(res实例)对于每个端点方法都是活着的,但我不知道如何使它成为全局的.

try {
    app.get('/webhook', function (req, res) {
        webhook.register(req, res);
    });

    app.get('/send', function (req, res) {
        sendAutoMessage('1004426036330995');
    });

    app.post('/webhook/subscribe', function (req, res) {
        webhook.subscribe("test");
    });

    app.post('/webhook/unsubscribe', function (req, res) {
        webhook.unsubscribe("test");
    });
} catch (error) {
    //response to user with 403 error and details
}
Run Code Online (Sandbox Code Playgroud)

小智 7

try catch无法异步捕获错误.这将有效:

app.get('/webhook', function (req, res) {
        try { 
          //enter code here
        } catch (error) {
          // something here
        }
    });
Run Code Online (Sandbox Code Playgroud)

但它是本地的而不是最好的方式.

好的方法是制作错误处理中间件功能.它是全球性的.毕竟你需要定义它app.use()并路由调用.

    app.use(function(err, req, res, next) {
      // This is error handler
    });
Run Code Online (Sandbox Code Playgroud)

您可以像往常一样向客户端发送包含错误详情的html页面.

此外,默认情况下,Express具有内置错误处理程序.错误将通过堆栈跟踪写入客户端(它在生产模式下不起作用).


xab*_*xab 7

有一个库(express-async-errors)可以满足您的需求。这使您能够编写异步路由处理程序,而无需将语句包装在 try/catch 块中,并使用全局错误处理程序捕获它们。要完成这项工作,您必须:
1. 安装express-async-errors
2. 导入包(在路由之前)
3. 设置全局快速错误处理程序
4. 编写异步路由处理程序(有关此的更多信息

用法示例:

import express from 'express';
import 'express-async-errors';

const app = express();

// route handlers must be async
app.get('/webhook', async (req, res) => {
    webhook.register(req, res);
});

app.get('/send', async (req, res) => {
    sendAutoMessage('1004426036330995');
});

app.post('/webhook/subscribe', async (req, res) => {
    webhook.subscribe("test");
});

app.post('/webhook/unsubscribe', async (req, res) => {
    webhook.unsubscribe("test");
});

// Global error handler - route handlers/middlewares which throw end up here
app.use((err, req, res, next) => {
    // response to user with 403 error and details
});

Run Code Online (Sandbox Code Playgroud)