NodeJS and pg promise, catch PostgreSQL exceptions

I am running NodeJS and pg-prom with the PostgreSQL backend. I created my own TRIGGER, which in some cases throws an exception. For this purpose, everything works fine.

But with pg-prom, I have problems finding the name of the error.

Using this code:

... .catch(function(err) { console.log(err); }); 

I get the following output:

 [ { success: false, result: { [error: vote_limit_exceeded] name: 'error', length: 80, severity: 'ERROR', code: 'P0001', detail: undefined, hint: undefined, position: undefined, internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'pl_exec.c', line: '3068', routine: 'exec_stmt_raise' } } ] 

I can see the name "vote_limit_exceeded" in the context, but how do I get back as a text string?

I tried to close:

 console.log(err[0].result); 

But I can not get the highlighted "vote_limit_exceeded".

+6
source share
1 answer

This is a standard PostgreSQL error view that has an invisible message property, so calling error.message will give you the expected result.

It is best to log your errors as follows:

 console.log(error.message || error); 

Extending the code of your code ...

It looks like your error context comes from the result of calling the batch function. This means that in this context, you can also call error.getErrors()[0] to get the very first error found.

Thus, for your specific case, safe error logging will be:

 .catch(error => { if (Array.isArray(error) && 'getErrors' in error) { // the error came from method `batch`; // let log the very first error: error = error.getErrors()[0]; } console.log("ERROR:", error.message || error); }); 

And of course, you can easily modify it to record all errors returned by the batch method.

This question gave me an idea of ​​adding the message property to the result of the rejection. There is always room for improvement;)

UPDATE

After that I updated spex.batch rejected the implementation to support the first and message properties, to simplify error handling and released it as version 0.4.3 . The implementation is even better than I originally planned, because first and message support nested batch results.

If you upgrade pg-promise to version 4.1.10 (or later), you can log such errors in general:

 .catch(error => { console.log("ERROR:", error.message || error); }); 

It always logs the correct error message, even if the error comes from a batch nested call.

+4
source

All Articles