简体   繁体   English

如何在 NestJs 中捕获 Typeorm 事务错误

[英]How to catch a Typeorm transaction error in NestJs

I have a server side written in node.js and nestJs, querying with typeorm.我有一个用 node.js 和 nestJs 编写的服务器端,用 typeorm 查询。

I'm trying to wrap some query's to the database with transaction as suggested here with some changes inspired by typeorm's docs , like this:我正在尝试按照此处的建议使用事务将一些查询包装到数据库中,并进行一些受 typeorm 文档启发的更改,如下所示:

getManager().transaction(async transactionalEntityManager => {
    transactionalEntityManager.save<Entity>(newEntity)
    transactionalEntityManager.save<Entity1>(newEntity1)
});

The transaction works well and rollback the database if there was an error.事务运行良好并在出现错误时回滚数据库。 tested this way:这样测试:

getManager().transaction(async transactionalEntityManager => {
    transactionalEntityManager.save<Entity>(newEntity)
    throw 'There is an error'
    transactionalEntityManager.save<Entity1>(newEntity1)
});

The execution of the transaction is inside a graphQL Mutation, so I should return an error to the client if something went wrong, the problem is that I can't catch the errors from the transaction.事务的执行在一个 graphQL Mutation 中,所以如果出现问题,我应该向客户端返回一个错误,问题是我无法从事务中捕获错误。

Tried doing this:尝试这样做:

  @Mutation(returns => Entity)
  async create(): Promise<Entity> {
    let entity = null;
    let error = null;
    getManager().transaction(async transactionalEntityManager => {
      try {
        entity = await transactionalEntityManager.save<Entity>(newEntity)
        await transactionalEntityManager.save<Entity1>(newEntity1);
      } catch (err) {
        error = err
      }
    })
    if (error) {
      return error
    }
    return entity
  }

when I throw error I catch it successfully, but when a real error occurs I can console.log() it in the server but it never reaches to return to the client.当我抛出错误时,我成功捕获了它,但是当发生真正的错误时,我可以在服务器中使用console.log()它,但它永远不会返回到客户端。

You are not awaiting your transaction to finish thus, the exception can be thrown after your function call end and you don't get the exception.您不是在等待事务完成,因此可以在函数调用结束后抛出异常并且您不会收到异常。

Just await your transaction and it should be fine.等待您的交易,应该没问题。

await getManager().transaction(async transactionalEntityManager => {
  ...
  throw 'ERROR THAT SHOULD BE CATCHED'
}

Also it returns the result of the inner function so it can be useful.它还返回内部函数的结果,因此它很有用。

const ok = await getManager().transaction(async transactionalEntityManager => {
  await transactionalEntityManager.save<Entity>(newEntity)
  await transactionalEntityManager.save<Entity>(newEntity2)
  return 'OK'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM