【问题标题】:How to use TypeORM transactions?如何使用 TypeORM 交易?
【发布时间】:2022-09-26 04:54:58
【问题描述】:

我在 TypeORM 中遇到事务问题,下面是示例代码:

const someFunction = async () => {
    try {
        await this.entityManager.transaction(async (manager) => {
            //some operations on manager

           if (something) {
               throw new Error(\'error\')
           }
        })
    } catch (error) {
        console.log(error);
    }
}

有人能告诉我为什么,当上面if 语句中的错误抛出时,我的整个 NestJS 应用程序都崩溃了,我必须重新启动这个应用程序?也许我不好尝试停止交易?如何正确管理事务并触发回滚?

谢谢你的帮助!

  • 我想这取决于你如何打电话给someFunction。只要来自 TypeORM 的transaction 在其回调中引发异常,这个函数本身就可以正常工作(不确定是否是这种情况)

标签: typescript transactions nestjs typeorm


【解决方案1】:

尝试删除 try/catch 块,事务应该捕获未处理的错误

const someFunction = async () => {
  await this.entityManager.transaction(async (manager) => {
    //some operations on manager

    if (something) {
      throw new Error('error')
    }
  })
}

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2023-03-13
    • 2014-01-30
    • 2012-05-08
    • 1970-01-01
    • 2022-10-24
    • 2019-10-11
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多