Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Friendly Error Message in Knex Transaction

I am using transactions in Knex to delete and update some data, which works fine, but occasionally there are errors thrown from one of the internal processes. I am able to capture errors and react to them, but I seem to be unable to get the "friendly" error message that describes the error. Here is an example:

The transaction code:

try {
    const trxResponse = await this.knex.transaction(async (trx) => {

        // ... do some stuff ...

        // Error is thrown within this operation
        return await trx(this.tableName)
            .insert(data)
            .returning(this.fieldsToReturn);
    });

    return trxResponse;

} catch (err) {
    console.log('handled', err, JSON.stringify(err), err.message);
    throw new QueryError();
}

The above console.log prints the following values for each (these are the real errors):

err: { error: invalid input value for enum relationship: "yourself"... /* stack trace */ <-- I need this text without the stack trace

JSON.stringify(err): {"name":"error","length":102,"severity":"ERROR","code":"22P02","file":"enum.c","line":"60","routine":"enum_in"}

err.message: insert into "beneficiary" ("application", "email", "firstName", "lastName", "middleInitial", "percentage", "relationship", "suffix") values ($1, $2, $3, $4, $5, $6, $7, $8), ($9, $10, $11, $12, $13, $14, $15, $16) returning "firstName", "lastName", "suffix", "middleInitial", "email", "percentage", "relationship" - invalid input value for enum relationship: "yourself"

What I really need is the "error" text that displays when you console.log(err) above. How do I pull just this string from the error? I cannot figure out how to get just that string.

Thanks!

like image 385
Chris Gilardi Avatar asked Oct 28 '25 13:10

Chris Gilardi


1 Answers

There were some discussions regarding error messages, and code. And I like the proposal made by @jmm

But, unfortunately, I can't see any other progress on it.

At this moment, I'm using some "hard coded" check:

...
try {
  await knex.insert(...);
catch (err) {
  if (err.message.includes('already exists')) {
    return "The item already exists";
  } else {
    return "DB Error";
  }
}

PS. I also find this library, but I didn't test it, and it looks abandoned a while ago.

like image 178
Kostanos Avatar answered Oct 30 '25 02:10

Kostanos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!