Skip to content

🎥 Make videos programmatically with React

`@remotion/media-utils`: Improve error handling when passing a non-existent file

Jonny Burger84df946c853d
diff --git a/packages/media-utils/src/get-audio-duration-in-seconds.ts b/packages/media-utils/src/get-audio-duration-in-seconds.ts
index 387320f729..20e23cc9be 100644
--- a/packages/media-utils/src/get-audio-duration-in-seconds.ts
+++ b/packages/media-utils/src/get-audio-duration-in-seconds.ts
@@ -1,4 +1,5 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
+import {onMediaError} from './media-tag-error-handling';
import {pLimit} from './p-limit';
const limit = pLimit(3);
@@ -18,8 +19,13 @@ const fn = (src: string): Promise<number> => {
audio.src = src;
return new Promise<number>((resolve, reject) => {
const onError = () => {
- reject(audio.error);
- cleanup();
+ onMediaError({
+ error: audio.error!,
+ src,
+ cleanup,
+ reject,
+ api: 'getAudioDurationInSeconds()',
+ });
};
const onLoadedMetadata = () => {
diff --git a/packages/media-utils/src/get-video-metadata.ts b/packages/media-utils/src/get-video-metadata.ts
index 7bde83e239..2a31187914 100644
--- a/packages/media-utils/src/get-video-metadata.ts
+++ b/packages/media-utils/src/get-video-metadata.ts
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import {isRemoteAsset} from './is-remote-asset';
+import {onMediaError} from './media-tag-error-handling';
import {pLimit} from './p-limit';
import type {VideoMetadata} from './types';
@@ -20,8 +21,13 @@ const fn = (src: string): Promise<VideoMetadata> => {
video.src = src;
return new Promise<VideoMetadata>((resolve, reject) => {
const onError = () => {
- reject(video.error);
- cleanup();
+ onMediaError({
+ error: video.error!,
+ src,
+ cleanup,
+ reject,
+ api: 'getVideoMetadata()',
+ });
};
const onLoadedMetadata = () => {
diff --git a/packages/media-utils/src/media-tag-error-handling.ts b/packages/media-utils/src/media-tag-error-handling.ts
new file mode 100644
index 0000000000..e32bddb1a1
--- /dev/null
+++ b/packages/media-utils/src/media-tag-error-handling.ts
@@ -0,0 +1,101 @@
+async function fetchWithTimeout(
+ url: string,
+ options: FetchRequestInit,
+ timeout = 3000,
+) {
+ const controller = new AbortController();
+ const id = setTimeout(() => controller.abort(), timeout);
+ options.signal = controller.signal;
+
+ try {
+ const response = await fetch(url, options);
+ clearTimeout(id);
+ return response;
+ } catch (e) {
+ clearTimeout(id);
+ throw new Error(`Fetch timed out after ${timeout}ms`);
+ }
+}
+
+const checkFor404 = (src: string) => {
+ return fetchWithTimeout(src, {
+ method: 'HEAD',
+ mode: 'no-cors',
+ }).then((res) => res.status);
+};
+
+const checkFor404OrSkip = async ({
+ suspecting404,
+ sameOrigin,
+ src,
+}: {
+ suspecting404: boolean;
+ sameOrigin: boolean;
+ src: string;
+}) => {
+ if (!suspecting404) {
+ return Promise.resolve(null);
+ }
+
+ if (!sameOrigin) {
+ return Promise.resolve(null);
+ }
+
+ try {
+ return await checkFor404(src);
+ } catch (e) {
+ return Promise.resolve(null);
+ }
+};
+
+export const onMediaError = ({
+ error,
+ src,
+ reject,
+ cleanup,
+ api,
+}: {
+ error: MediaError;
+ src: string;
+ reject: (reason: unknown) => void;
+ cleanup: () => void;
+ api: string;
+}) => {
+ const suspecting404 = error?.MEDIA_ERR_SRC_NOT_SUPPORTED === error?.code;
+ const isSrcSameOriginAsCurrent = new URL(src, window.location.origin)
+ .toString()
+ .startsWith(window.location.origin);
+ checkFor404OrSkip({
+ suspecting404,
+ sameOrigin: isSrcSameOriginAsCurrent,
+ src,
+ })
+ .then((status) => {
+ const err =
+ status === 404
+ ? new Error(
+ [
+ `Failed to execute ${api}: Received a 404 error loading "${src}".`,
+ 'Correct the URL of the file.',
+ ].join(' '),
+ )
+ : new Error(
+ [
+ `Failed to execute ${api}, Received a MediaError loading "${src}".`,
+ status === null
+ ? `Browser error message: ${error?.message}`
+ : `HTTP Status code of the file: ${status}.`,
+ 'Check the path of the file and if it is a valid video.',
+ ]
+ .filter(Boolean)
+ .join(' '),
+ );
+ reject(err);
+ cleanup();
+ console.log('404', status);
+ })
+ .catch((e) => {
+ reject(e);
+ cleanup();
+ });
+};