Search code examples
javascriptgraphqlnestjstypeorm

How to catch a Typeorm transaction error in NestJs


I have a server side written in node.js and nestJs, querying with 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:

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.

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.


Solution

  • 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'
    }