import { ErrorType , MLErrorObject , isBoomError , isErrorString , isErrorMessage , isEsErrorBody , isMLResponseError , } from './types' ; import { isPopulatedObject } from '../object_utils' ; export const extractErrorProperties = ( error ) : MLErrorObject => { if ( isEsErrorBody ( error ) ) { return { message : error . error . reason , statusCode : error . status , fullError : error , } ; } if ( isErrorString ( error ) ) { return { message : error , } ; } if ( isBoomError ( error ) ) { return { message : error . output . payload . message , statusCode : error . output . payload . statusCode , } ; } if ( error ?. body === undefined && ! error ?. message ) { return { message : '' , } ; } if ( typeof error . body === 'string' ) { return { message : error . body , } ; } if ( isMLResponseError ( error ) ) { if ( typeof error . body . attributes === 'object' && typeof error . body . attributes . body ?. error ?. reason === 'string' ) { const errObj = { message : error . body . attributes . body . error . reason , statusCode : error . body . statusCode , fullError : error . body . attributes . body , } ; if ( typeof error . body . attributes . body . error . caused_by === 'object' && ( typeof error . body . attributes . body . error . caused_by ?. reason === 'string' || typeof error . body . attributes . body . error . caused_by ?. caused_by ?. reason === 'string' ) ) { errObj . causedBy = error . body . attributes . body . error . caused_by ?. caused_by ?. reason || error . body . attributes . body . error . caused_by ?. reason ; } if ( Array . isArray ( error . body . attributes . body . error . root_cause ) && typeof error . body . attributes . body . error . root_cause [ 0 ] === 'object' && isPopulatedObject ( error . body . attributes . body . error . root_cause [ 0 ] , [ 'script' ] ) ) { errObj . causedBy = error . body . attributes . body . error . root_cause [ 0 ] . script ; errObj . message += `: '${ error . body . attributes . body . error . root_cause [ 0 ] . script }'` ; } return errObj ; } else { return { message : error . body . message , statusCode : error . body . statusCode , } ; } } if ( isErrorMessage ( error ) ) { return { message : error . message , } ; } return { message : '' , } ; } ; export const extractErrorMessage = ( error ) : string => { const errorObj = extractErrorProperties ( error ) ; return errorObj . message ; } ;