我想从 twitter-API-client 获取有关最近 3 个关注者的数据。
async function get_followers() {
const followers = await twitterClient.accountsAndUsers
.followersList({
count: 3,
});
console.log(followers);
}
// call function
get_followers();
软件包已正确安装。但显示错误
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Object>".] {
code: 'ERR_UNHANDLED_REJECTION'
}
我使用的是节点 v 8.12.1
仅凭这些错误信息,这些错误可能很难追踪,因此您需要更好地处理未捕获的异常。
所以,第一步就是这样。出于某种原因,这通常比那更能说明问题。我不明白为什么类似的功能没有默认嵌入到节点中。这是一个基本的实现,但是您可以通过抓住承诺来获取更多信息。
process.on('unhandledRejection', (reason, promise) => {
console.log(reason, promise);
// Application specific error-handling here
});
这对于未处理的异常非常有用。这也将防止这些错误导致服务器崩溃。
对于我的服务器,在启动时会检查某些配置。如果他们没有通过,我希望服务器崩溃。
所以我创建了一个类。有几种方法可以做到这一点,但这对我有用
export class ServerCrasher {
public obj: any;
constructor(obj: any) {
this.obj = obj
}
}
当我想要一个异常使服务器崩溃时,我将其包装在 ServerCrasher 中并运行这样的代码。
process.on('unhandledRejection', (reason, promise) => {
promise.catch(async (e: any) => {
if (e instanceof ServerCrasher) {
ColorLog(['bgRed', "Server Forcefully Crashed due to uncaught promise exception."])
ColorLog(['red', e.obj])
let i = 0;
try {
while (i < 200 && serverProcess === undefined) {
await asyncDelay(500);
i++;
}
// serverProcess is my https-server, obviously
serverProcess?.close(async () => {
ColorLog(['gray', 'Server taken offline.']);
await asyncDelay(1000)
process.exit(0);
});
} catch (error) {
ColorLog(['gray', 'Failed to gracefully take the server offline']);
ColorLog(['gray', error]);
process.exit(2);
}
return;
}
// Simple logging of the error, but the server stays online
ColorLog(['bgRed', reason])
ColorLog(['red', e])
})
});
请注意,ColorLog 是我的实现,基于其他人的代码。您可以使用您喜欢的任何日志记录,或者从这里复制我的(或其他人的)。
最后,这是asyncDelay
export function asyncDelay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}