import { errors as opensearchErrors } from '@elastic/elasticsearch' ; import { get } from 'lodash' ; const responseErrors = { isServiceUnavailable : ( statusCode ) => statusCode === 503 , isConflict : ( statusCode ) => statusCode === 409 , isNotAuthorized : ( statusCode ) => statusCode === 401 , isForbidden : ( statusCode ) => statusCode === 403 , isRequestEntityTooLarge : ( statusCode ) => statusCode === 413 , isNotFound : ( statusCode ) => statusCode === 404 , isBadRequest : ( statusCode ) => statusCode === 400 , isTooManyRequests : ( statusCode ) => statusCode === 429 , } ; const { ConnectionError , NoLivingConnectionsError , TimeoutError } = opensearchErrors ; const SCRIPT_CONTEXT_DISABLED_REGEX = /(?:cannot execute scripts using \[)([a-z]*)(?:\] context)/ ; const INLINE_SCRIPTS_DISABLED_MESSAGE = 'cannot execute [inline] scripts' ; import { SavedObjectsErrorHelpers } from './errors' ; type OpenSearchErrors = opensearchErrors . ConnectionError | opensearchErrors . NoLivingConnectionsError | opensearchErrors . TimeoutError | opensearchErrors . ResponseError ; export function decorateOpenSearchError ( error ) { if ( ! ( error instanceof Error ) ) { throw new Error ( 'Expected an instance of Error' ) ; } const { reason } = get ( error , 'body.error' , { reason : undefined } ) as { reason ? : string ; } ; if ( error instanceof ConnectionError || error instanceof NoLivingConnectionsError || error instanceof TimeoutError || responseErrors . isServiceUnavailable ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateOpenSearchUnavailableError ( error , reason ) ; } if ( responseErrors . isConflict ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateConflictError ( error , reason ) ; } if ( responseErrors . isNotAuthorized ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateNotAuthorizedError ( error , reason ) ; } if ( responseErrors . isForbidden ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateForbiddenError ( error , reason ) ; } if ( responseErrors . isRequestEntityTooLarge ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateRequestEntityTooLargeError ( error , reason ) ; } if ( responseErrors . isNotFound ( error . statusCode ) ) { return SavedObjectsErrorHelpers . createGenericNotFoundError ( ) ; } if ( responseErrors . isTooManyRequests ( error . statusCode ) ) { return SavedObjectsErrorHelpers . decorateTooManyRequestsError ( error , reason ) ; } if ( responseErrors . isBadRequest ( error . statusCode ) ) { if ( SCRIPT_CONTEXT_DISABLED_REGEX . test ( reason || '' ) || reason === INLINE_SCRIPTS_DISABLED_MESSAGE ) { return SavedObjectsErrorHelpers . decorateOpenSearchCannotExecuteScriptError ( error , reason ) ; } return SavedObjectsErrorHelpers . decorateBadRequestError ( error , reason ) ; } return SavedObjectsErrorHelpers . decorateGeneralError ( error , reason ) ; }