Skip to content

Commit f730aa7

Browse files
meyer9soedirgo
andauthored
fix: Ensure thrown errors have a stack trace (#502)
* Ensure thrown errors have a stack trace * chore: stricter typing * chore: update snapshot --------- Co-authored-by: Bobbie Soedirgo <[email protected]>
1 parent 197b4d2 commit f730aa7

File tree

3 files changed

+29
-9
lines changed

3 files changed

+29
-9
lines changed

src/PostgrestBuilder.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import nodeFetch from '@supabase/node-fetch'
33

44
import type { Fetch, PostgrestSingleResponse } from './types'
5+
import PostgrestError from './PostgrestError'
56

67
export default abstract class PostgrestBuilder<Result>
78
implements PromiseLike<PostgrestSingleResponse<Result>>
@@ -156,7 +157,7 @@ export default abstract class PostgrestBuilder<Result>
156157
}
157158

158159
if (error && this.shouldThrowOnError) {
159-
throw error
160+
throw new PostgrestError(error)
160161
}
161162
}
162163

src/PostgrestError.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import type { PostgrestError as IPostgrestError } from './types'
2+
3+
export default class PostgrestError extends Error implements IPostgrestError {
4+
details: string
5+
hint: string
6+
code: string
7+
8+
constructor(context: IPostgrestError) {
9+
super(context.message)
10+
this.name = 'PostgrestError'
11+
this.details = context.details
12+
this.hint = context.hint
13+
this.code = context.code
14+
}
15+
}

test/basic.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -631,20 +631,24 @@ test('throwOnError throws errors instead of returning them', async () => {
631631
try {
632632
await postgrest.from('missing_table').select().throwOnError()
633633
} catch (error) {
634-
expect(error).toMatchInlineSnapshot(`
635-
Object {
636-
"code": "42P01",
637-
"details": null,
638-
"hint": null,
639-
"message": "relation \\"public.missing_table\\" does not exist",
640-
}
641-
`)
634+
expect(error).toMatchInlineSnapshot(
635+
`[PostgrestError: relation "public.missing_table" does not exist]`
636+
)
642637
isErrorCaught = true
643638
}
644639

645640
expect(isErrorCaught).toBe(true)
646641
})
647642

643+
test('throwOnError throws errors which include stack', async () => {
644+
try {
645+
await postgrest.from('does_not_exist').select().throwOnError()
646+
} catch (err) {
647+
expect(err instanceof Error).toBe(true)
648+
expect((err as Error).stack).not.toBeUndefined()
649+
}
650+
})
651+
648652
// test('throwOnError setting at the client level - query', async () => {
649653
// let isErrorCaught = false
650654
// const postgrest_ = new PostgrestClient<Database>(REST_URL, { throwOnError: true })

0 commit comments

Comments
 (0)