Error handling

Errors signaled by PostgreSQL will be converted into an Emacs Lisp error that subclasses pg-error. You can handle these errors as usual in Emacs Lisp, as shown in the example below.

Basic error handling

ELISP> (ignore-errors (pg-exec *pg* "SELECT ###"))
nil
ELISP> (condition-case nil
           (pg-exec *pg* "SELECT ###")
         (pg-error 42))
42 (#o52, #x2a, ?*)

Some errors are converted into specific subclasses of pg-error, as listed below. We can discriminate the error category thanks to [PostgreSQL’s SQLSTATE support](See https://www.postgresql.org/docs/17/errcodes-appendix.html).

Error classMeaning
pg-connection-errorConnection failure
pg-invalid-passwordInvalid password or authentication data
pg-feature-not-supportedPostgreSQL feature not supported
pg-syntax-errorSyntax error
pg-undefined-tableUndefined table
pg-undefined-columnUndefined column
pg-undefined-functionUndefined function
pg-copy-failedPostgreSQL COPY failed
pg-connect-timeoutPostgreSQL connection attempt timed out
pg-type-errorWhen serializing, an argument was of an unexpected type
pg-numeric-value-out-of-rangeNumeric value out of range
pg-division-by-zeroDivision by zero
pg-floating-point-exceptionFloating point exception
pg-array-subscript-errorArray subscript error
pg-datetime-field-overflowOverflow in a datetime field
pg-invalid-text-representationInvalid text representation
pg-invalid-binary-representationInvalid binary representation
pg-datatype-mismatchDatatype mismatch
pg-json-errorJSON-related error
pg-integrity-constraint-violationViolation of an integrity constraint
pg-restrict-violationRestrict violation
pg-not-null-violationViolation of a not NULL constraint
pg-foreign-key-violationViolation of a FOREIGN KEY constraint
pg-unique-violationViolation of a UNIQUE constraint
pg-check-violationViolation of a CHECK constraint
pg-exclusion-violationViolation of an exclusion constraint
pg-transaction-timeoutTransaction timeout
pg-insufficient-resourcesInsufficient resources on the backend server (eg. memory full)
pg-disk-fullDisk full on the backend server
pg-too-many-connectionsToo many connections to the backend
pg-internal-errorInternal error in the backend

You can undertake error handling for specific error categories as shown in the example below:

Differentiated error handling

ELISP> (condition-case nil
           (pg-exec *pg* "SELECT 2147483649::int4")
         (pg-numeric-value-out-of-range (message "Numeric overflow"))
	 (pg-syntax-error (message "Syntax error"))
	 (pg-error (message "Generic error")))
"Numeric overflow"

Please note that some semi-compatible PostgreSQL variants do not implement fine-grained SQLSTATE error reporting, simply returning all errors as an “internal error” (this is the case of CrateDB in 2025-02, for example).