调试未处理的承诺拒绝

Debug Unhandled Promise Rejections

我已写信给以下数据库查询以取回具有特定偏移量的所有帖子:

async function getPaginationPosts(start, size) {
    try {
        const posts = await knex("posts").select().where({
            deleted: false,
        }).orderBy("createdAt").limit(size).offset(start)
    } catch (e) {
        console.log(e.message)
        console.log(e.stack)
    }
    return posts
}

但是,我得到以下 Unhandled Promise Rejection

(node:1824) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: posts is n
ot defined
(node:1824) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.

我的问题是我没有在控制台中获得有关该错误的任何进一步信息。

您网站的任何建议:

  1. 如何正确调试这些类型的拒绝?
  2. 上面的代码有什么问题?

预先感谢您的回复!

更新

我将函数更改为以下内容:

async function getPaginationPosts(size, offset) {
    try {
        return await knex("posts").select().where({
            deleted: false,
        }).orderBy("createdAt").limit(size).offset(offset)
    } catch (e) {
        console.log(e.message)
        console.log(e.stack)
        return null
    }
}

现在我收到以下异常:

(node:9096) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: start is n
ot defined

我的函数中没有使用变量 start

对我做错了什么有什么建议吗?

posts 的定义不正确。将它们定义在 try/catch 块之外或 return 来自 try 块的结果:

async function getPaginationPosts(start, size) {
    try {
        return await knex("posts").select().where({
            deleted: false,
        }).orderBy("createdAt").limit(size).offset(start)
    } catch (e) {
        console.log(e.message)
        console.log(e.stack)
        return null
    }
}

或者:

async function getPaginationPosts(start, size) {
    let posts
    try {
        posts = await knex("posts").select().where({
            deleted: false,
        }).orderBy("createdAt").limit(size).offset(start)
    } catch (e) {
        console.log(e.message)
        console.log(e.stack)
    }
    return posts
}

记录未处理的拒绝的一种便捷方式是添加侦听器(通常在您的应用程序的入口点,即 main.js),如下所示

process.on("unhandledRejection", (error) => {
  console.error(error); // This prints error with stack included (as for normal errors)
  throw error; // Following best practices re-throw error and let the process exit with error code
});