Improve CORS messages (#134659)

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Christos Nasikas 2022-06-21 11:04:38 +03:00 committed by GitHub
parent d13d997d4c
commit e1f3aca0c8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 0 deletions

View file

@ -146,6 +146,14 @@ export const API_INFO_ERROR = (status: number) =>
defaultMessage: 'Received status: {status} when attempting to get application information',
});
export const FETCH_ERROR = i18n.translate(
'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.fetchErrorMsg',
{
defaultMessage:
'Failed to fetch. Check the URL or the CORS configuration of your ServiceNow instance.',
}
);
export const INSTALLATION_CALLOUT_TITLE = i18n.translate(
'xpack.triggersActionsUI.components.builtinActionTypes.servicenow.installationCalloutTitle',
{

View file

@ -99,4 +99,28 @@ describe('useGetAppInfo', () => {
})
).rejects.toThrow('An error occurred');
});
it('it throws an error when fetch fails', async () => {
expect.assertions(1);
getAppInfoMock.mockImplementation(() => {
const error = new Error('An error occurred');
error.name = 'TypeError';
throw error;
});
const { result } = renderHook<UseGetAppInfoProps, UseGetAppInfo>(() =>
useGetAppInfo({
actionTypeId,
http,
})
);
await expect(() =>
act(async () => {
await result.current.fetchAppInfo(actionConnector);
})
).rejects.toThrow(
'Failed to fetch. Check the URL or the CORS configuration of your ServiceNow instance.'
);
});
});

View file

@ -10,6 +10,7 @@ import { useState, useEffect, useRef, useCallback } from 'react';
import { HttpStart } from '@kbn/core/public';
import { getAppInfo } from './api';
import { AppInfo, RESTApiError, ServiceNowActionConnector } from './types';
import { FETCH_ERROR } from './translations';
export interface UseGetAppInfoProps {
actionTypeId?: string;
@ -56,6 +57,18 @@ export const useGetAppInfo = ({ actionTypeId, http }: UseGetAppInfoProps): UseGe
if (!didCancel.current) {
setIsLoading(false);
}
/**
* According to https://developer.mozilla.org/en-US/docs/Web/API/fetch#exceptions
* all network errors throw a TypeError. Usually fetch errors are happening
* due to CORS misconfiguration. By detecting fetch errors we can provide
* a better message about CORS. Adding a CORS rule to allow requests from the UI
* in the ServiceNow instance is needed by our ServiceNow applications.
*/
if (error.name === 'TypeError') {
throw new Error(FETCH_ERROR);
}
throw error;
}
},