UNPKG

@bitblit/ratchet-common

Version:

Common tools for general use

60 lines 2.07 kB
import { Logger } from '../logger/logger.js'; import { StringRatchet } from './string-ratchet.js'; import { ErrorHandlingApproach } from './error-handling-approach.js'; import { LoggerLevelName } from '../logger/logger-level-name.js'; export class ErrorRatchet { static handleErrorByApproach(err, approach, level = LoggerLevelName.error, formatMsg = 'Error: %s') { if (err && approach) { if (approach === ErrorHandlingApproach.LogAndSwallow || approach === ErrorHandlingApproach.LogAndPassThru) { Logger.logByLevel(level, formatMsg, err, err); } if (approach === ErrorHandlingApproach.PassThru || approach === ErrorHandlingApproach.LogAndPassThru) { throw err; } } else { Logger.error('Cannot handle error %s - %s, missing either error or approach', err, approach); } } static safeStringifyErr(err, log = true) { let rval = 'ERR WAS NULL'; if (err) { if (err['message']) { rval = err['message']; } else { try { rval = JSON.stringify(err); } catch (err2) { Logger.error('Failed to json stringify: %s', err2); rval = String(err); } } } if (log) { Logger.error('%s', rval, err); } return rval; } static asErr(input) { let rval = null; if (input) { if (input instanceof Error) { rval = input; } else { rval = new Error('Force-Cast to error : ' + String(input)); } } return rval; } static fErr(format, ...input) { const msg = StringRatchet.format(format, ...input); return new Error(msg); } static throwFormattedErr(format, ...input) { throw ErrorRatchet.fErr(format, ...input); } } //# sourceMappingURL=error-ratchet.js.map