-
Notifications
You must be signed in to change notification settings - Fork 10
feat: implement structured error handling #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| 'fireworkers': minor | ||
| --- | ||
|
|
||
| Add `FirestoreError` with a stable `code` field (compatible with the Firebase Web SDK's `FirestoreErrorCode`) so callers can branch on a kebab-cased code instead of regex-matching `.message`. Also exposes `status` (canonical status string, e.g. `'NOT_FOUND'`) and `httpCode` (HTTP status) for debugging. Network failures wrap into `FirestoreError` with `code: 'unavailable'`. Non-breaking — `FirestoreError` extends `Error` and `err.message` still equals the REST response's `error.message`. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { clearFirestore, initDb } from '../tests/unit/helpers'; | ||
| import { create } from './create'; | ||
| import { FirestoreError, safe_fetch, status_to_code } from './error'; | ||
| import { get } from './get'; | ||
| import { remove } from './remove'; | ||
| import type { DB } from './types'; | ||
| import { update } from './update'; | ||
|
|
||
| let db: DB; | ||
|
|
||
| describe('FirestoreError', () => { | ||
| beforeAll(async () => { | ||
| db = await initDb(); | ||
| }); | ||
| beforeEach(clearFirestore); | ||
|
|
||
| it('throws a FirestoreError with code "not-found" when getting a missing document', async () => { | ||
| let caught: unknown; | ||
| try { | ||
| await get(db, 'todos', 'does-not-exist'); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| expect(caught).toBeInstanceOf(Error); | ||
| const err = caught as FirestoreError; | ||
| expect(err.code).toBe('not-found'); | ||
| expect(err.status).toBe('NOT_FOUND'); | ||
| expect(err.name).toBe('FirestoreError'); | ||
| expect(err.message).toMatch(/./); | ||
| }); | ||
|
|
||
| it('throws a FirestoreError with code "not-found" when updating a missing document', async () => { | ||
| let caught: unknown; | ||
| try { | ||
| await update(db, 'todos', 'does-not-exist', { completed: true }); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| const err = caught as FirestoreError; | ||
| expect(err.code).toBe('not-found'); | ||
| }); | ||
|
|
||
| it('throws a FirestoreError for unauthenticated/permission-denied requests', async () => { | ||
| const bad_db: DB = { project_id: db.project_id, jwt: 'not-a-valid-jwt' }; | ||
|
|
||
| let caught: unknown; | ||
| try { | ||
| await create(bad_db, 'todos', { title: 'x', completed: false }); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| const err = caught as FirestoreError; | ||
| // Emulator may surface bad-auth as any of these depending on why it rejects | ||
| // (missing/malformed/expired token vs. rule violation). | ||
| expect(['unauthenticated', 'permission-denied', 'invalid-argument']).toContain(err.code); | ||
| }); | ||
|
|
||
| it('throws a FirestoreError when remove is called with an invalid JWT', async () => { | ||
| const bad_db: DB = { project_id: db.project_id, jwt: 'not-a-valid-jwt' }; | ||
|
|
||
| let caught: unknown; | ||
| try { | ||
| await remove(bad_db, 'todos', 'any-id'); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| const err = caught as FirestoreError; | ||
| expect(['unauthenticated', 'permission-denied', 'invalid-argument']).toContain(err.code); | ||
| }); | ||
|
|
||
| it('preserves the original REST error message', async () => { | ||
| let caught: FirestoreError | undefined; | ||
| try { | ||
| await get(db, 'todos', 'does-not-exist'); | ||
| } catch (err) { | ||
| caught = err as FirestoreError; | ||
| } | ||
|
|
||
| expect(caught?.message.length).toBeGreaterThan(0); | ||
| }); | ||
| }); | ||
|
|
||
| describe('status_to_code', () => { | ||
| it('maps known canonical status strings to kebab-case codes', () => { | ||
| expect(status_to_code('NOT_FOUND')).toBe('not-found'); | ||
| expect(status_to_code('PERMISSION_DENIED')).toBe('permission-denied'); | ||
| expect(status_to_code('FAILED_PRECONDITION')).toBe('failed-precondition'); | ||
| expect(status_to_code('UNAUTHENTICATED')).toBe('unauthenticated'); | ||
| }); | ||
|
|
||
| it('falls back to "unknown" for unrecognized status strings', () => { | ||
| expect(status_to_code('NOT_A_REAL_STATUS')).toBe('unknown'); | ||
| expect(status_to_code('')).toBe('unknown'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('safe_fetch', () => { | ||
| afterEach(() => { | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it('wraps network-level fetch rejections in a FirestoreError with code "unavailable"', async () => { | ||
| vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('Failed to connect')); | ||
|
|
||
| let caught: unknown; | ||
| try { | ||
| await safe_fetch('https://example.invalid'); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| const err = caught as FirestoreError; | ||
| expect(err.code).toBe('unavailable'); | ||
| expect(err.message).toBe('Failed to connect'); | ||
| expect(err.httpCode).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('falls back to a generic message when the thrown value is not an Error', async () => { | ||
| vi.spyOn(globalThis, 'fetch').mockRejectedValue('raw rejection'); | ||
|
|
||
| let caught: unknown; | ||
| try { | ||
| await safe_fetch('https://example.invalid'); | ||
| } catch (err) { | ||
| caught = err; | ||
| } | ||
|
|
||
| expect(caught).toBeInstanceOf(FirestoreError); | ||
| const err = caught as FirestoreError; | ||
| expect(err.code).toBe('unavailable'); | ||
| expect(err.message).toBe('Network request failed'); | ||
| }); | ||
|
|
||
| it('returns the Response unchanged when fetch resolves', async () => { | ||
| const response = new Response('ok', { status: 200 }); | ||
| vi.spyOn(globalThis, 'fetch').mockResolvedValue(response); | ||
|
|
||
| await expect(safe_fetch('https://example.invalid')).resolves.toBe(response); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import type { Status } from './types'; | ||
|
|
||
| /** | ||
| * String error codes mirroring the Firebase Web SDK's `FirestoreErrorCode`. | ||
| * The 16 canonical status codes, kebab-cased. | ||
| * | ||
| * Reference: {@link https://firebase.google.com/docs/reference/js/firestore_.firestoreerror#firestoreerrorcode} | ||
| */ | ||
| export type FirestoreErrorCode = | ||
| | 'cancelled' | ||
| | 'unknown' | ||
| | 'invalid-argument' | ||
| | 'deadline-exceeded' | ||
| | 'not-found' | ||
| | 'already-exists' | ||
| | 'permission-denied' | ||
| | 'resource-exhausted' | ||
| | 'failed-precondition' | ||
| | 'aborted' | ||
| | 'out-of-range' | ||
| | 'unimplemented' | ||
| | 'internal' | ||
| | 'unavailable' | ||
| | 'data-loss' | ||
| | 'unauthenticated'; | ||
|
|
||
| const STATUS_TO_CODE: Record<string, FirestoreErrorCode> = { | ||
| CANCELLED: 'cancelled', | ||
| UNKNOWN: 'unknown', | ||
| INVALID_ARGUMENT: 'invalid-argument', | ||
| DEADLINE_EXCEEDED: 'deadline-exceeded', | ||
| NOT_FOUND: 'not-found', | ||
| ALREADY_EXISTS: 'already-exists', | ||
| PERMISSION_DENIED: 'permission-denied', | ||
| RESOURCE_EXHAUSTED: 'resource-exhausted', | ||
| FAILED_PRECONDITION: 'failed-precondition', | ||
| ABORTED: 'aborted', | ||
| OUT_OF_RANGE: 'out-of-range', | ||
| UNIMPLEMENTED: 'unimplemented', | ||
| INTERNAL: 'internal', | ||
| UNAVAILABLE: 'unavailable', | ||
| DATA_LOSS: 'data-loss', | ||
| UNAUTHENTICATED: 'unauthenticated', | ||
| }; | ||
|
|
||
| /** | ||
| * Maps a canonical Firestore status string (e.g. `'NOT_FOUND'`) to the | ||
| * kebab-cased error code. Unrecognized values fall back to `'unknown'`. | ||
| */ | ||
| export const status_to_code = (status: string): FirestoreErrorCode => | ||
| STATUS_TO_CODE[status] ?? 'unknown'; | ||
|
|
||
| /** | ||
| * Error thrown by every `fireworkers` operation when Firestore rejects a | ||
| * request or the network request fails. Shape mirrors the Firebase Web SDK's | ||
| * `FirestoreError` so callers can branch on `err.code`. | ||
| */ | ||
| export class FirestoreError extends Error { | ||
| readonly code: FirestoreErrorCode; | ||
| readonly httpCode?: number; | ||
| readonly status?: string; | ||
|
|
||
| constructor({ | ||
| code, | ||
| message, | ||
| httpCode, | ||
| status, | ||
| }: { | ||
| code: FirestoreErrorCode; | ||
| message: string; | ||
| httpCode?: number; | ||
| status?: string; | ||
| }) { | ||
| super(message); | ||
| this.name = 'FirestoreError'; | ||
| this.code = code; | ||
| this.httpCode = httpCode; | ||
| this.status = status; | ||
| } | ||
| } | ||
|
|
||
| const is_error_response = (data: unknown): data is { error: Status } => | ||
| data !== null && | ||
| typeof data === 'object' && | ||
| 'error' in data && | ||
| typeof (data as { error: unknown }).error === 'object' && | ||
| (data as { error: unknown }).error !== null; | ||
|
|
||
| /** | ||
| * Inspects a parsed REST response body and throws a `FirestoreError` if it | ||
| * contains an `error` object. Otherwise narrows `data` to the success shape. | ||
| */ | ||
| export function throw_if_error<T>(data: T | { error: Status }): asserts data is T { | ||
| if (!is_error_response(data)) return; | ||
|
|
||
| const { code: httpCode, message, status } = data.error; | ||
|
|
||
| throw new FirestoreError({ | ||
| code: typeof status === 'string' ? status_to_code(status) : 'unknown', | ||
| httpCode, | ||
| status, | ||
| message: message ?? 'Unknown Firestore error', | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * `fetch` wrapper that converts network-level rejections (e.g. DNS failure, | ||
| * connection reset) into a `FirestoreError` with code `'unavailable'` so | ||
| * consumers have a single error type to catch. | ||
| */ | ||
| export const safe_fetch = async ( | ||
| input: URL | RequestInfo, | ||
| init?: RequestInit | ||
| ): Promise<Response> => { | ||
| try { | ||
| return await fetch(input, init); | ||
| } catch (err) { | ||
| throw new FirestoreError({ | ||
| code: 'unavailable', | ||
| message: err instanceof Error ? err.message : 'Network request failed', | ||
| }); | ||
| } | ||
|
besart-finsweet marked this conversation as resolved.
|
||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.