diff --git a/src/lib/types.ts b/src/lib/types.ts index d41bc074..a83707d3 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -54,11 +54,23 @@ export abstract class PostgrestBuilder implements PromiseLike | Partial[] + protected shouldThrowOnError?: boolean constructor(builder: PostgrestBuilder) { Object.assign(this, builder) } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): PostgrestBuilder { + this.shouldThrowOnError = true + return this + } + then, TResult2 = never>( onfulfilled?: | ((value: PostgrestResponse) => TResult1 | PromiseLike) @@ -92,7 +104,8 @@ export abstract class PostgrestBuilder implements PromiseLike implements PromiseLike = { @@ -112,6 +129,7 @@ export abstract class PostgrestBuilder implements PromiseLike { expect(res).toMatchSnapshot() }) +test('throwOnError throws errors instead of returning them', async () => { + let isErrorCaught = false + + try { + await postgrest.from('missing_table').select().throwOnError() + } catch (error) { + expect(error).toMatchSnapshot() + isErrorCaught = true + } + + expect(isErrorCaught).toBe(true) +}) + test('connection error', async () => { const postgrest = new PostgrestClient('http://this.url.does.not.exist') let isErrorCaught = false @@ -107,6 +120,20 @@ test('connection error', async () => { expect(isErrorCaught).toBe(true) }) +test('connection errors should work the same with throwOnError', async () => { + const postgrest = new PostgrestClient('http://this.url.does.not.exist') + let isErrorCaught = false + await postgrest + .from('user') + .select() + .throwOnError() + .then(undefined, (error) => { + expect(error).toMatchSnapshot() + isErrorCaught = true + }) + expect(isErrorCaught).toBe(true) +}) + test('custom type', async () => { interface User { username: string