const extractCausedByChain = ( causedBy = { } , accumulator = [ ] ) : any => { const { reason , caused_by } = causedBy ; if ( reason ) { accumulator . push ( reason ) ; } if ( caused_by ) { return extractCausedByChain ( caused_by , accumulator ) ; } return accumulator ; } ; param err param statusCodeToMessageMap return export const wrapEsError = ( err , statusCodeToMessageMap = { } ) => { const { statusCode , response } = err ; const { error : { root_cause = [ ] , caused_by = { } , } = { } , } = typeof response === 'string' ? JSON . parse ( response ) : response ; if ( ! statusCodeToMessageMap [ statusCode ] ) { const error = { statusCode } ; const causedByChain = extractCausedByChain ( caused_by ) ; const defaultCause = root_cause . length ? extractCausedByChain ( root_cause [ 0 ] ) : err . message ; error . cause = causedByChain . length ? causedByChain : defaultCause ; return error ; } const message = statusCodeToMessageMap [ statusCode ] ; return { message , statusCode } ; } ;