Skip to content

Commit

Permalink
fix: Ensure thrown errors have a stack trace (#502)
Browse files Browse the repository at this point in the history
* Ensure thrown errors have a stack trace

* chore: stricter typing

* chore: update snapshot

---------

Co-authored-by: Bobbie Soedirgo <[email protected]>
  • Loading branch information
meyer9 and soedirgo authored Jan 15, 2024
1 parent 197b4d2 commit f730aa7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
3 changes: 2 additions & 1 deletion src/PostgrestBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import nodeFetch from '@supabase/node-fetch'

import type { Fetch, PostgrestSingleResponse } from './types'
import PostgrestError from './PostgrestError'

export default abstract class PostgrestBuilder<Result>
implements PromiseLike<PostgrestSingleResponse<Result>>
Expand Down Expand Up @@ -156,7 +157,7 @@ export default abstract class PostgrestBuilder<Result>
}

if (error && this.shouldThrowOnError) {
throw error
throw new PostgrestError(error)
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/PostgrestError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { PostgrestError as IPostgrestError } from './types'

export default class PostgrestError extends Error implements IPostgrestError {
details: string
hint: string
code: string

constructor(context: IPostgrestError) {
super(context.message)
this.name = 'PostgrestError'
this.details = context.details
this.hint = context.hint
this.code = context.code
}
}
20 changes: 12 additions & 8 deletions test/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,20 +631,24 @@ test('throwOnError throws errors instead of returning them', async () => {
try {
await postgrest.from('missing_table').select().throwOnError()
} catch (error) {
expect(error).toMatchInlineSnapshot(`
Object {
"code": "42P01",
"details": null,
"hint": null,
"message": "relation \\"public.missing_table\\" does not exist",
}
`)
expect(error).toMatchInlineSnapshot(
`[PostgrestError: relation "public.missing_table" does not exist]`
)
isErrorCaught = true
}

expect(isErrorCaught).toBe(true)
})

test('throwOnError throws errors which include stack', async () => {
try {
await postgrest.from('does_not_exist').select().throwOnError()
} catch (err) {
expect(err instanceof Error).toBe(true)
expect((err as Error).stack).not.toBeUndefined()
}
})

// test('throwOnError setting at the client level - query', async () => {
// let isErrorCaught = false
// const postgrest_ = new PostgrestClient<Database>(REST_URL, { throwOnError: true })
Expand Down

0 comments on commit f730aa7

Please sign in to comment.