diff --git a/.changeset/use-api-holder-no-throw.md b/.changeset/use-api-holder-no-throw.md index 72a2874798..465cc9f401 100644 --- a/.changeset/use-api-holder-no-throw.md +++ b/.changeset/use-api-holder-no-throw.md @@ -1,5 +1,6 @@ --- '@backstage/frontend-plugin-api': patch +'@backstage/core-plugin-api': patch --- Changed `useApiHolder` to return an empty `ApiHolder` instead of throwing when used outside of an API context. diff --git a/packages/core-app-api/src/apis/system/ApiProvider.test.tsx b/packages/core-app-api/src/apis/system/ApiProvider.test.tsx index 4273587c00..0a899ff88a 100644 --- a/packages/core-app-api/src/apis/system/ApiProvider.test.tsx +++ b/packages/core-app-api/src/apis/system/ApiProvider.test.tsx @@ -114,12 +114,16 @@ describe('ApiProvider', () => { withLogCollector(['error'], () => { expect(() => { render(); - }).toThrow(/^API context is not available/); + }).toThrow('No implementation available for apiRef{x}'); }).error, ).toEqual([ - expect.stringContaining('Error: API context is not available'), + expect.stringContaining( + 'Error: No implementation available for apiRef{x}', + ), expect.objectContaining({ type: 'unhandled-exception' }), - expect.stringContaining('Error: API context is not available'), + expect.stringContaining( + 'Error: No implementation available for apiRef{x}', + ), expect.objectContaining({ type: 'unhandled-exception' }), expect.stringContaining( 'The above error occurred in the component', @@ -130,12 +134,16 @@ describe('ApiProvider', () => { withLogCollector(['error'], () => { expect(() => { render(); - }).toThrow(/^API context is not available/); + }).toThrow('No implementation available for apiRef{x}'); }).error, ).toEqual([ - expect.stringContaining('Error: API context is not available'), + expect.stringContaining( + 'Error: No implementation available for apiRef{x}', + ), expect.objectContaining({ type: 'unhandled-exception' }), - expect.stringContaining('Error: API context is not available'), + expect.stringContaining( + 'Error: No implementation available for apiRef{x}', + ), expect.objectContaining({ type: 'unhandled-exception' }), expect.stringContaining( 'The above error occurred in the component', diff --git a/packages/frontend-plugin-api/src/apis/system/useApi.tsx b/packages/frontend-plugin-api/src/apis/system/useApi.tsx index ffb458d7f3..2ecdc7e6be 100644 --- a/packages/frontend-plugin-api/src/apis/system/useApi.tsx +++ b/packages/frontend-plugin-api/src/apis/system/useApi.tsx @@ -32,7 +32,11 @@ export function useApiHolder(): ApiHolder { return emptyApiHolder; } - return versionedHolder.atVersion(1) ?? emptyApiHolder; + const apiHolder = versionedHolder.atVersion(1); + if (!apiHolder) { + throw new NotImplementedError('ApiContext v1 not available'); + } + return apiHolder; } /**