Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tangy-bees-follow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/shared': minor
---

Improve error handling when loading clerk-js.
9 changes: 5 additions & 4 deletions packages/shared/src/__tests__/loadClerkJsScript.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ClerkRuntimeError } from '../error';
import {
buildClerkJsScriptAttributes,
clerkJsScriptUrl,
Expand Down Expand Up @@ -86,8 +87,8 @@ describe('loadClerkJsScript(options)', () => {
rejectedWith = error;
}

expect(rejectedWith).toBeInstanceOf(Error);
expect(rejectedWith.message).toBe('Clerk: Failed to load Clerk');
expect(rejectedWith).toBeInstanceOf(ClerkRuntimeError);
expect(rejectedWith.message).toContain('Clerk: Failed to load Clerk');
expect((window as any).Clerk).toBeUndefined();
});

Expand Down Expand Up @@ -137,8 +138,8 @@ describe('loadClerkJsScript(options)', () => {
await loadPromise;
fail('Should have thrown error');
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toBe('Clerk: Failed to load Clerk');
expect(error).toBeInstanceOf(ClerkRuntimeError);
expect((error as Error).message).toContain('Clerk: Failed to load Clerk');
// The malformed Clerk object should still be there since it was set
expect((window as any).Clerk).toEqual({ status: 'ready' });
}
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/errors/runtimeError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ export class ClerkRuntimeError extends Error {
*/
code: string;

constructor(message: string, { code }: { code: string }) {
/**
* The original error that was caught to throw an instance of ClerkRuntimeError.
*/
cause?: Error;

constructor(message: string, { code, cause }: { code: string; cause?: Error }) {
const prefix = '🔒 Clerk:';
const regex = new RegExp(prefix.replace(' ', '\\s*'), 'i');
const sanitized = message.replace(regex, '');
Expand All @@ -27,6 +32,7 @@ export class ClerkRuntimeError extends Error {

Object.setPrototypeOf(this, ClerkRuntimeError.prototype);

this.cause = cause;
this.code = code;
this.message = _message;
this.clerkRuntimeError = true;
Expand Down
15 changes: 10 additions & 5 deletions packages/shared/src/loadClerkJsScript.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { ClerkOptions, SDKMetadata, Without } from '@clerk/types';

import { buildErrorThrower } from './error';
import { buildErrorThrower, ClerkRuntimeError } from './error';
import { createDevOrStagingUrlCache, parsePublishableKey } from './keys';
import { loadScript } from './loadScript';
import { isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';
import { addClerkPrefix } from './url';
import { versionSelector } from './versionSelector';

const FAILED_TO_LOAD_ERROR = 'Clerk: Failed to load Clerk';
const ERROR_CODE = 'failed_to_load_clerk_js';
const ERROR_CODE_TIMEOUT = 'failed_to_load_clerk_js_timeout';
Comment on lines +10 to +11
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this helping because we want to better track why an error is thrown ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct 👍

const FAILED_TO_LOAD_ERROR = 'Failed to load Clerk';

const { isDevOrStagingUrl } = createDevOrStagingUrlCache();

Expand Down Expand Up @@ -96,7 +98,7 @@ function waitForClerkWithTimeout(timeoutMs: number): Promise<HTMLScriptElement |
cleanup(timeoutId, pollInterval);

if (!isClerkProperlyLoaded()) {
reject(new Error(FAILED_TO_LOAD_ERROR));
reject(new ClerkRuntimeError(FAILED_TO_LOAD_ERROR, { code: ERROR_CODE_TIMEOUT }));
} else {
resolve(null);
}
Expand Down Expand Up @@ -162,8 +164,11 @@ const loadClerkJsScript = async (opts?: LoadClerkJsScriptOptions): Promise<HTMLS
crossOrigin: 'anonymous',
nonce: opts.nonce,
beforeLoad: applyClerkJsScriptAttributes(opts),
}).catch(() => {
throw new Error(FAILED_TO_LOAD_ERROR);
}).catch(error => {
throw new ClerkRuntimeError(FAILED_TO_LOAD_ERROR + (error.message ? `, ${error.message}` : ''), {
code: ERROR_CODE,
cause: error,
});
});

return loadPromise;
Expand Down
6 changes: 3 additions & 3 deletions packages/shared/src/loadScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function loadScript(src = '', opts: LoadScriptOptions): Promise<HTM
}

if (!document || !document.body) {
reject(NO_DOCUMENT_ERROR);
reject(new Error(NO_DOCUMENT_ERROR));
}

const script = document.createElement('script');
Expand All @@ -37,9 +37,9 @@ export async function loadScript(src = '', opts: LoadScriptOptions): Promise<HTM
resolve(script);
});

script.addEventListener('error', () => {
script.addEventListener('error', event => {
script.remove();
reject();
reject(event.error ?? new Error(`failed to load script: ${src}`));
});

script.src = src;
Expand Down
Loading