PgError.js is an error class for Node.js that parses PostgreSQL's ErrorResponse format and names its fields with human readable properties. It's most useful when combined with Brian Carlson's Node.js PostgreSQL client library to get structured and identifiable PostgreSQL errors. Supports all fields returned by PostgreSQL up to v9.4.
The PostgreSQL client library does return an
Error object with some fields
set, but it's not a dedicated object for easy
instanceof identification nor
does it yet support all field types. I've found it immensely useful to be
strict and classify errors beforehand when building fault tolerant systems. That
helps programmatically decide whether to wrap, escalate or handle a particular
npm install pg-error
PgError.js follows semantic versioning, so feel free to
depend on its major version with something like
>= 1.0.0 < 2 (a.k.a
var PgError =var error =M: "null value in column \"name\" violates not-null constraint"S: "ERROR"C: "23502"error instanceof PgError // => trueerror instanceof Error // => trueerrormessage // => "null value in column \"name\" violates not-null constraint"errorseverity // => "ERROR"errorcode // => 23502
var msg = "MWash your teeth!\0SWARNING\0\0"var error = PgErrorerrormessage // => "Wash your teeth!"errorseverity // => "WARNING"
The client does its error and notice parsing on the
You can get an active instance of it after connecting from
var Pg =var pg = host: "/tmp" database: "pg_error_test"var connection = pgconnection
You'll have to swap out two functions,
Pg.Connection.prototype.parseN, for parsing errors and notices respectively:
connectionparseE = PgErrorparseconnectionparseN = PgErrorparse
However, the way the client is built, it will start emitting those errors and
notices under the
PgError event name. Until that's improved in the
Pg.Connection class, you'll need to re-emit those under the correct
That's it. Your Pg query errors should now be instances of
PgError and with
all the human readable field names.
Properties on an instance of PgError
For descriptions of the properties, please see PostgreSQL's Error and Notice Message Fields.
|condition||Code name in lowercase according to errcodes.txt.|
|position||P||Position parsed to a
|internalPosition||p||Internal position parsed to a
|line||L||Line parsed to a
PgError.js is released under a Lesser GNU Affero General Public License, which in summary means:
- You can use this program for no cost.
- You can use this program for both personal and commercial reasons.
- You do not have to share your own program's code which uses this program.
- You have to share modifications (e.g. bug-fixes) you've made to this program.
For more convoluted language, see the