使用node-fetch处理http请求,网络出错的时候返回错误:
request to http://xxx/blur/get failed, reason: getaddrinfo ENOTFOUND
at ClientRequest.<anonymous> (file:///Users/project/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:513:28)
at Socket.socketErrorListener (node:_http_client:481:9)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
erroredSysCall: 'getaddrinfo'
}
然后node进程就退出了。
处理了catch:
fetch(GET_URL)
.then(res => res.json())
.then(json => {
//logic
})
.catch(err => {console.log(err)});
......
process.on('uncaughtException', function(error){
console.log('uncaughtException', error);
});
依然会退出,
我的预期是不要让它退出node进程,如何处理?
参考GPT和自己的思路:
要防止Node异常退出的最好方法是通过添加异常处理程序来捕获错误。在你的情况下,你已经在代码中添加了一个异常处理程序,但它似乎没有正确地捕获错误。
你可以尝试使用以下代码替换你的 process.on()
方法来捕获所有未处理的 Promise 中的错误:
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// 对错误进行处理,比如记录日志、重启进程等
});
这个事件处理程序将捕获所有未处理的 Promise 中的错误,并在 Node 记录到控制台或日志中。此外,如果需要可以通过记录日志、发送通知或重启进程等方式来处理错误。
如果你不确定 Promise 为什么会引发错误,可以在 Promise 中添加一个 .catch()
方法来捕获错误并处理它。例如:
fetch(GET_URL)
.then(res => res.json())
.then(json => {
// logic
})
.catch(err => {
console.log('Error caught:', err.message);
// 处理错误,比如记录日志、重启进程等
});
注意,使用 unhandledRejection
并不会防止 Node 进程异常退出,只会将错误捕获到控制台或日志中供参考。为了防止 Node 进程异常退出,你也可以使用 try-catch
语句直接捕获错误并进行处理。例如:
try {
const res = await fetch(GET_URL);
const json = await res.json();
// logic
} catch (err) {
console.log('Error caught:', err.message);
// 处理错误,比如记录日志、重启进程等
}
总之,为了防止 Node 进程异常退出,请确保捕获所有可能引发错误的地方,并适当地处理错误。
参考GPT和自己的思路:
通过捕获unhandledRejection事件可以防止Node进程异常退出。修改你的代码如下:
process.on('unhandledRejection', (error) => {
console.log('unhandledRejection', error);
});
fetch(GET_URL)
.then(res => res.json())
.then(json => {
//logic
})
.catch(err => {
console.log(err);
throw err; //抛出错误
});
使用上述代码,当请求出错时,Node进程不会退出,而是会触发unhandledRejection事件,这样你就能在事件处理器里查看并处理错误了。同时,你还需要在catch块中抛出异常,这样可以让事件处理器识别该异常并处理。