I’m writing a service in Nestjs which uses typeorm to communicate with a MySQL server. Say, I create a table, test_table
with two columns col1
and col2
, col1
having a UNIQUE
constraint.
If try to insert a duplicate value I get an error which looks like:
{
query: 'INSERT INTO `test_table`(`col1`, `col2`) VALUES (?, ?)',
parameters: [ 'test-val-1', 'test-val-2' ],
driverError: {
code: 'ER_DUP_ENTRY',
errno: 1062,
sqlState: '23000',
sqlMessage: "Duplicate entry 'test-val-1' for key 'test_table.col1'",
sql: "INSERT INTO `test_table`(`col1`, `col2`) VALUES ('test-val-1', 'test-val-2')"
},
code: 'ER_DUP_ENTRY',
errno: 1062,
sqlState: '23000',
sqlMessage: "Duplicate entry 'test-val-1' for key 'test_table.col1'",
sql: "INSERT INTO `test_table`(`col1`, `col2`) VALUES ('test-val-1', 'test-val-2')"
}
If I return sqlMessage
it exposes the table name and column name, I don’t get the name of the erroneous column explicitly.
Is there a way to extract information in a format such that I can have the column name which is causing the error and what error is it causing?
There are two solutions I can think of:
-
Checking for duplicate entry by hitting the db before trying to insert. It will increase latency because of additional database calls.
-
Or I can write a parser which extracts the relevant information from the message but it seems like going overboard because if the message changes for some reason, it breaks.