NodeJs :将我"unhandledRejection"承诺保存到文本文件



我有一个愚蠢的问题。。。

我没能保存我的";unhandledRejection";文本文件出错。。。

我使用NodeJs程序与Winston一起处理日志,并且:

  • 我设法用控制台在屏幕上显示未处理的拒绝错误。error(error(

  • 但我无法将此内容保存到日志文件中。。。当我使用logger.info(错误(时,它会向我显示文字:

[object Promise]

屏幕错误

-->如何正确地捕捉这些错误并将其保存到日志中?

感谢

编辑:这是一个代码示例。只需将您的记录器配置文件放在";const-logger=";部分


"use strict";
// Load external files
const ethers = require("ethers");
// logging config
const logger = require("put here your logger file config");
process.on('unhandledRejection', (reason, promise) => {
console.log("")
logger.error('----- ERROR : more details below -----')
logger.info('----- Unhandled Rejection at -----')
logger.info(promise)
logger.info('----- Reason -----')
logger.info(reason)
console.log("")
})
const provider = new ethers.providers.WebSocketProvider("wss://ws-matic-mainnet.chainstacklabs.com");
function startSniper() {
provider._websocket.on("open", async () => {
launch_nonce = await provider.getTransactionCount(dummy);
});
};

// START the bot
startSniper();

编辑2:新的片段试图应用你不可能的修复。。。还是我错了??

// TRYING TO APPLY YOUR SOLUTION
"use strict";
// Load external files
const ethers = require("ethers");
// logging config
const logger = require("put here your logger file config");
process.on('unhandledRejection', (reason, promise) => {
console.log("")
logger.error('----- ERROR : more details below -----')
logger.info('----- Unhandled Rejection at -----')
const resolvedPromise = await promise // this solution does not work ! Error : 'await' expressions are only allowed within async functions and at the top levels of modules.
logger.info(resolvedPromise)
logger.info('----- Reason -----')
logger.info(reason)
console.log("")
})
const provider = new ethers.providers.WebSocketProvider("wss://ws-matic-mainnet.chainstacklabs.com");
async function startSniper() {
provider._websocket.on("open", async () => {
launch_nonce = await provider.getTransactionCount(dummy);
});
};

// START the bot
startSniper();

如果您有一个Promise,但想要从中获取值,则需要等待该Promise得到解决或拒绝。在这种情况下,拒绝是一个问题。在JavaScript中有两种处理方法。

const promise = fetchSomeData()
const promise2 = fetchSomeOtherData()
let data, data2
// use await to process promise, catch any errors
try {
data = await promise
} catch (error) {
logger.info(`Promise rejected - could not fetch data with error ${error}`)
}
//use then() to process promise, handle any errors
promise2.then(
(value) => { data2 = value },
(reason) => { logger.info(`Promise rejected - could not fetch data with reason ${reason}`) }
}
await promise2

如果你的记录器显示了一个promise对象,这意味着这个promise还没有被解决或拒绝,所以你需要一些代码来延迟程序执行,直到这两件事发生为止。


查看代码示例,尝试更改它,看看它是否适用于

const resolvedPromise = await promise
logger.info(resolvedPromise)

最新更新