import i18n from "./i18n.json" ; import { errorStatusCode } from "./errorStatusCode" ; import { logger } from "../logger" ; const errors = i18n . errors ; interface ErrorParam { errorKey : string ; values : string [ ] ; } param errorInstance export const getErrorMessage = ( errorInstance ) : string => { let key = "" ; let values = undefined ; if ( typeof errorInstance === "string" ) { key = errorInstance ; } else { key = errorInstance . errorKey ; values = errorInstance . values ; } if ( key in errors ) { let results = errors [ key ] ; if ( values ) { values . forEach ( ( val , i ) => { const re = new RegExp ( "\\{" + i + "}" , "g" ) ; results = results . replace ( re , val ) ; } ) ; } return `${ key }: ${ results }` ; } return key ; } ; class ErrorChain extends Error { errorCode : number ; details : string | undefined ; parent : ErrorChain | undefined ; constructor ( code , errorInstance ) { super ( "" ) ; this . errorCode = code ; this . message = this . getErrorMessage ( errorInstance ) ; } param errorInstance getErrorMessage ( errorInstance ) { return getErrorMessage ( errorInstance ) ; } param messages param padding messages ( results , padding ? ) { padding = padding || "" ; let mes = `${ padding }code: ${ this . errorCode }\n` + `${ padding }message: ${ this . message }` ; if ( this . details ) { mes += `\n${ padding }details: ${ this . details }` ; } results . push ( mes ) ; if ( this . parent ) { this . parent . messages ( results , padding + "  " ) ; } } } const isErrorChainObject = ( o ) : boolean => { return o instanceof ErrorChain ; } ; param code param errorKey param error export const build = ( code , errorKey , error ? ) : ErrorChain => { const oError = new ErrorChain ( code , errorKey ) ; if ( error ) { if ( isErrorChainObject ( error ) ) { oError . parent = error as ErrorChain ; } else { const e = error as Error ; oError . details = e ? e . message : "" ; } } return oError ; } ; param err export const log = ( err ) : string => { if ( isErrorChainObject ( err ) ) { const messages = [ ] ; ( err as ErrorChain ) . messages ( messages ) ; const msg = "\n" + messages . join ( "\n" ) ; logger . error ( msg ) ; return msg ; } else { logger . error ( err . message ) ; return err . message ; } } ;