express.js全局try/catch
我正在使用Express在Node JS上开发一个REST服务器.
I'm developing a rest server on Node JS with Express.
我正在尝试将所有端点包装在try \ catch块中,因此错误的中心点将向发送方发送详细信息. 我的问题是,每个终结点方法都响应(res实例),但是我不知道如何使其全局.
I'm trying to wrap all my endpoints in try\catch block, so a central point of error will response back to the sender with details. My problem that response (res instance) is alive for each of the endpoints methods, but I don't know how to make it global.
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
}
try catch
不能异步捕获错误.
这将起作用:
try catch
can not catch error asynchronously.
This will work:
app.get('/webhook', function (req, res) {
try {
//enter code here
} catch (error) {
// something here
}
});
但这是本地方法,而不是最佳方法.
But it is local and not the best way.
好的方法是使错误处理中间件功能.它是全球性的.您需要在所有app.use()
和路由呼叫之后定义它.
Good way is make error-handling middleware function. It is global. You need to define it after all app.use()
and routes calls.
app.use(function(err, req, res, next) {
// This is error handler
});
您可以像往常一样将带有错误详细信息的html页面发送给客户端.
You can send the html page with details of error to client as usual.
此外,默认情况下,Express具有内置的错误处理程序.该错误将通过堆栈跟踪写入客户端(在生产模式下不起作用).
Also, by default, Express have built-in error handler. The error will be written to the client with stack trace (It does not work in production mode).