NodeJS Restify 嵌套 Promise 错误处理
NodeJS Restify Nested Promise Error Handling
我已经为我的产品做了 API 的 restify。我已经安装了 loggly
和 newrelic
用于监控目的。
最近 newrelic
通知我,我的代码某处有错误。
app.get('/myroute', (req, res, next) => {
let payload = { /*...*/ };
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(/* some promise */)
.then(() => {
/* some code */
sendEmail({params}); // some error was thrown from one of the promise chain
// inside this function...
return something;
})
.then(/* some promise */)
.then(() => {
res.send(something);
})
.catch(next);
});
承诺链解决得很好,用户得到正确的响应,因为我没有 return sendEmail
函数。而且我不想,因为我不想让用户长时间等待响应。
function sendMail(params) {
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(() => {
params.abc.replace('a', 'b'); // error thrown, cannot find replace of undefined.
return something;
});
}
newrelic
捕获到错误,但 loggly
没有。我已经有 restify 的 formatters
设置,但它还不够,因为请求已成功处理并且没有落入 .catch(next)
.
我不想要修复 sendMail
函数的解决方案。如果有这样的错误,我只想记录一下。
有没有在不将 .catch()
到 sendMail
函数的情况下捕获并记录此类错误的方法?
我想通了。我正在尝试 process.on('uncaughtException')
来处理它。
但我遇到了 process.on('unhandledRejection')
完成了这项工作!
https://nodejs.org/api/process.html#process_event_unhandledrejection
我已经为我的产品做了 API 的 restify。我已经安装了 loggly
和 newrelic
用于监控目的。
最近 newrelic
通知我,我的代码某处有错误。
app.get('/myroute', (req, res, next) => {
let payload = { /*...*/ };
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(/* some promise */)
.then(() => {
/* some code */
sendEmail({params}); // some error was thrown from one of the promise chain
// inside this function...
return something;
})
.then(/* some promise */)
.then(() => {
res.send(something);
})
.catch(next);
});
承诺链解决得很好,用户得到正确的响应,因为我没有 return sendEmail
函数。而且我不想,因为我不想让用户长时间等待响应。
function sendMail(params) {
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(() => {
params.abc.replace('a', 'b'); // error thrown, cannot find replace of undefined.
return something;
});
}
newrelic
捕获到错误,但 loggly
没有。我已经有 restify 的 formatters
设置,但它还不够,因为请求已成功处理并且没有落入 .catch(next)
.
我不想要修复 sendMail
函数的解决方案。如果有这样的错误,我只想记录一下。
有没有在不将 .catch()
到 sendMail
函数的情况下捕获并记录此类错误的方法?
我想通了。我正在尝试 process.on('uncaughtException')
来处理它。
但我遇到了 process.on('unhandledRejection')
完成了这项工作!
https://nodejs.org/api/process.html#process_event_unhandledrejection