Transaction rollback: unhandled error in transaction
Quick summary
A SQL statement failed inside your transaction and the database rolled back all changes — the error was not caught and handled.
Why this happens
A SQL error occurred inside a transaction but was not caught, causing an automatic rollback
The transaction was not properly committed due to an exception before the commit statement
A constraint violation or type error in one statement invalidated the entire transaction block
Minimal example
const tx = await db.beginTransaction();
await tx.query('INSERT INTO orders (id, total) VALUES (1, 100)');
await tx.query('INSERT INTO items (order_id, name) VALUES (1, NULL)'); // NOT NULL violation
await tx.commit(); // never reached, transaction rolled backconst tx = await db.beginTransaction();
try {
await tx.query('INSERT INTO orders (id, total) VALUES (1, 100)');
await tx.query('INSERT INTO items (order_id, name) VALUES (1, ?)', ['item1']);
await tx.commit();
} catch (err) {
await tx.rollback();
console.error('Transaction failed, rolled back:', err.message);
}Wrapping the transaction in try/catch and explicitly rolling back on error prevents unhandled exceptions and gives control over the failure.
How to diagnose
Check the error message to identify which SQL statement failed within the transaction
Verify that all statements in the transaction are valid before starting the transaction
Log each statement execution to trace where the failure occurred
How to fix
Wrap each statement in try/catch and decide whether to rollback or continue based on the error
Validate data before the transaction to catch constraint violations early
Use savepoints to partially rollback a transaction instead of rolling back everything
How to prevent
Always handle transaction errors explicitly with try/catch and rollback in the catch block
Validate all data before starting a transaction to minimize the chance of mid-transaction failures
Related Resources
Related Glossary
Related Lessons
- Transactions
Learn about transaction handling.