From 0415b18a100043df164bcd40639f9373e3358350 Mon Sep 17 00:00:00 2001 From: "Mengdi \"Monday\" Chen" Date: Wed, 30 Mar 2022 11:07:12 -0400 Subject: [PATCH] [ReactDebugTools] add custom error type for future new hooks (#24168) * [ReactDebugTools] add custom error type for future new hooks * update per review comments * remove unused argument --- .../react-debug-tools/src/ReactDebugHooks.js | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/react-debug-tools/src/ReactDebugHooks.js b/packages/react-debug-tools/src/ReactDebugHooks.js index b7159859060e7..49bf65e3136fa 100644 --- a/packages/react-debug-tools/src/ReactDebugHooks.js +++ b/packages/react-debug-tools/src/ReactDebugHooks.js @@ -356,6 +356,23 @@ const Dispatcher: DispatcherType = { useId, }; +// create a proxy to throw a custom error +// in case future versions of React adds more hooks +const DispatcherProxyHandler = { + get(target, prop) { + if (target.hasOwnProperty(prop)) { + return target[prop]; + } + const error = new Error('Missing method in Dispatcher: ' + prop); + // Note: This error name needs to stay in sync with react-devtools-shared + // TODO: refactor this if we ever combine the devtools and debug tools packages + error.name = 'UnsupportedFeatureError'; + throw error; + }, +}; + +const DispatcherProxy = new Proxy(Dispatcher, DispatcherProxyHandler); + // Inspect export type HookSource = { @@ -664,7 +681,7 @@ export function inspectHooks( const previousDispatcher = currentDispatcher.current; let readHookLog; - currentDispatcher.current = Dispatcher; + currentDispatcher.current = DispatcherProxy; let ancestorStackError; try { ancestorStackError = new Error(); @@ -708,7 +725,7 @@ function inspectHooksOfForwardRef( ): HooksTree { const previousDispatcher = currentDispatcher.current; let readHookLog; - currentDispatcher.current = Dispatcher; + currentDispatcher.current = DispatcherProxy; let ancestorStackError; try { ancestorStackError = new Error();