diff --git a/.changeset/short-rats-remember.md b/.changeset/short-rats-remember.md new file mode 100644 index 00000000..710c093a --- /dev/null +++ b/.changeset/short-rats-remember.md @@ -0,0 +1,5 @@ +--- +"@slonik/pg-driver": minor +--- + +expose DatabaseError diff --git a/packages/pg-driver/README.md b/packages/pg-driver/README.md index 17e28b30..46456444 100644 --- a/packages/pg-driver/README.md +++ b/packages/pg-driver/README.md @@ -3,4 +3,43 @@ ```ts import { createPgDriverFactory, -} from '@slonik/pg-driver'; \ No newline at end of file + DatabaseError, +} from '@slonik/pg-driver'; +``` + +## Error handling + +All Slonik errors extend from `SlonikError`. `SlonikError` uses `cause` property to store the original error, which might be a `DatabaseError` from `pg`. Example: + +```ts +pool.on('error', (error) => { + const cause = error.cause; + + if (cause instanceof DatabaseError) { + console.log(cause.code); + } +}); +``` + +This allows you to handle errors based on the lower-level error codes provided by `pg` driver. + +Example of handling all errors that could warrant a fatal error: + +```ts +const fatalErrorClasses = [ + // Connection Exception + '08', + // Invalid Authorization Specification + '28', +]; + +pool.on('error', (error) => { + if (error.cause instanceof DatabaseError) { + const classCode = error.cause.code.slice(0, 2); + + if (fatalErrorClasses.includes(classCode)) { + // Initiate shutdown due to unexpected connection state. + } + } +}); +``` \ No newline at end of file diff --git a/packages/pg-driver/src/index.ts b/packages/pg-driver/src/index.ts index 82de48c9..1c6a85c3 100644 --- a/packages/pg-driver/src/index.ts +++ b/packages/pg-driver/src/index.ts @@ -1 +1,2 @@ export { createPgDriverFactory } from './factories/createPgDriverFactory'; +export { DatabaseError } from 'pg';