jeremydaly / data-api-client

A "DocumentClient" for the Amazon Aurora Serverless Data API
MIT License
439 stars 61 forks source link

Do I have to use try/catch in transactions? #71

Closed Ricardo1980 closed 3 years ago

Ricardo1980 commented 3 years ago

Hi!

I would like to use something like this:

let results = await mysql.transaction()
  .query('INSERT INTO myTable (name) VALUES(:name)', { name: 'Tiger' })
  .query('UPDATE myTable SET age = :age WHERE name = :name' { age: 4, name: 'Tiger' })
  .rollback((e,status) => { /* do something with the error */ }) // optional
  .commit() // execute the queries

but I want to throw an error using this, (when any error happens in that sequence) throw new error('Error executing transaction')

So, is it enough to put that inside the rollback or do I also have to use try/catch? Something like:

try {
let results = await mysql.transaction()
  .query('INSERT INTO myTable (name) VALUES(:name)', { name: 'Tiger' })
  .query('UPDATE myTable SET age = :age WHERE name = :name' { age: 4, name: 'Tiger' })
  .rollback((e,status) => { 
/* do something with the error */
    throw new error('Error executing transaction')
 }) // optional
  .commit() // execute the queries
} catch (e) {
   throw new error('Error executing transaction')
}

Thanks for clarification.

ffxsam commented 3 years ago

@Ricardo1980

The .rollback() method is only in case you want to do some sort of additional processing or error-handling. It's not intended to serve as a catch block. Don't throw an error from within the rollback. This is how I'd use it:

try {
  const results = await mysql.transaction()
    .query('INSERT INTO myTable (name) VALUES(:name)', { name: 'Tiger' })
    .query('UPDATE myTable SET age = :age WHERE name = :name' { age: 4, name: 'Tiger' })
    .rollback((e,status) => { 
      // Log error to Sentry, for example, or set a variable
      Sentry.captureException(e, { extra: /* some metadata */ });
    })
  .commit() // execute the queries
} catch (e) {
   throw new error('Error executing transaction')
}
Ricardo1980 commented 3 years ago

Thanks a lot! I saw that because I didn't have the beginTransaction permission. Thanks.