import { ValidationError } from 'class-validator' ; import { snakeCase , toUpper } from 'lodash' ; param exResponse returns export function getCode ( exResponse ) { if ( typeof exResponse === 'string' ) { return formatErrorCode ( exResponse ) ; } if ( 'error' in exResponse && typeof exResponse . error === 'string' ) { return formatErrorCode ( exResponse . error ) ; } return '' ; } export function getErrorMessage ( exResponse ) { if ( typeof exResponse === 'string' ) { return exResponse ; } if ( typeof exResponse . message === 'string' ) { return exResponse . message ; } if ( Array . isArray ( exResponse . message ) ) { const error = exResponse . message [ 0 ] ; if ( typeof error === 'string' ) { return error ; } const validationError = parseErrorMessage ( error ) ; if ( validationError ) { return validationError ; } } return 'INTERNAL_SERVER_ERROR' ; } param error returns function formatErrorCode ( error ) { return toUpper ( snakeCase ( error ) ) ; } function parseErrorMessage ( error ) { let message = '' ; const messages = findConstraints ( error ) ; if ( messages === undefined ) { return 'Invalid parameter' ; } Object . keys ( messages ) . forEach ( ( key ) : void => { message += `${ message === '' ? '' : ' -- ' }${ messages [ key ] }` ; } ) ; return message ; } /**
 * Find contraints in an error oject
 */ function findConstraints ( error ) { let objectToIterate = error ; while ( objectToIterate . children !== undefined ) { objectToIterate = objectToIterate . children [ 0 ] ; } return objectToIterate . constraints ; } /**
 * Contraints of the validation
 */ interface Constraint { [ type ] : string ; } /**
 * Exception response
 */ interface ExceptionResponse { error ? : string ; message ? : string | string [ ] | ValidationError [ ] ; }