Skip to content

Commit

Permalink
feat: expose @slonik/pg-driver DatabaseError
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Nov 14, 2024
1 parent 4cf9b37 commit 6aa21ad
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/short-rats-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@slonik/pg-driver": minor
---

expose DatabaseError
41 changes: 40 additions & 1 deletion packages/pg-driver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,43 @@
```ts
import {
createPgDriverFactory,
} from '@slonik/pg-driver';
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.
}
}
});
```
1 change: 1 addition & 0 deletions packages/pg-driver/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { createPgDriverFactory } from './factories/createPgDriverFactory';
export { DatabaseError } from 'pg';

0 comments on commit 6aa21ad

Please sign in to comment.