diff --git a/.changeset/polite-wolves-attack.md b/.changeset/polite-wolves-attack.md new file mode 100644 index 000000000..1a4922564 --- /dev/null +++ b/.changeset/polite-wolves-attack.md @@ -0,0 +1,5 @@ +--- +'@gitbook/runtime': minor +--- + +return 4xx error instead of 5xx when failed to extract access token diff --git a/packages/runtime/src/oauth.ts b/packages/runtime/src/oauth.ts index 71835c1a1..3f4647d27 100644 --- a/packages/runtime/src/oauth.ts +++ b/packages/runtime/src/oauth.ts @@ -185,7 +185,23 @@ export function createOAuthHandler( const json = await response.json(); // Store the credentials in the installation configuration - const credentials = await extractCredentials(json); + let credentials: RequestUpdateIntegrationInstallation; + try { + credentials = await extractCredentials(json); + } catch (error) { + logger.error(`extractCredentials error`, error.stack); + return new Response( + JSON.stringify({ + error: `Failed to retrieve access_token from OAuth response. Please try again.`, + }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + }, + } + ); + } logger.debug(`exchange code for credentials`, credentials); @@ -333,11 +349,15 @@ export async function getToken( return creds.configuration.oauth_credentials.access_token; } +/** + * Default implementation to extract the credentials from the OAuth response. + * throws an error if the `access_token` is not present in the response. + */ function defaultExtractCredentials(response: OAuthResponse): RequestUpdateIntegrationInstallation { if (!response.access_token) { - throw new Error( - `Could not extract access_token from response ${JSON.stringify(response, null, 4)}` - ); + const message = `Failed to retrieve access_token from response`; + logger.error(`${message} ${JSON.stringify(response, null, 2)} `); + throw new Error(message); } return {