UNPKG

@napp/exception

Version:

common exception. node application common library. serialization error

134 lines (133 loc) 3.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Exception = exports.ExceptionParser = void 0; class ExceptionParser { resolve(e, err) { if (err === null || err === void 0 ? void 0 : err.name) e.name = '' + err.name; if (err === null || err === void 0 ? void 0 : err.code) e.code = '' + err.code; if (err === null || err === void 0 ? void 0 : err.cause) e.cause = err.cause; // if (err?.stack) e.stack = err.stack; // if (err?.data) e.data = err.data; // if (err?.source) e.source = err.source; return e; } parse(err) { if (err instanceof Exception) { return err; } if (err instanceof Error) { let e = new Exception(err.message, { name: "exception", source: err }); return this.resolve(e, err); } if (err && err.message) { let e = new Exception(err.message, { name: "exception", source: err }); return this.resolve(e, err); } return false; } } exports.ExceptionParser = ExceptionParser; class Exception extends Error { constructor(msg, opt) { if (Array.isArray(msg) && msg.length === 2) { super(msg[1]); this.code = msg[0]; } else { super(msg); } if (opt && opt.name) { this.name = opt.name; } else { this.name = "exception"; } if (opt && opt.code) { this.setCode(opt.code); } if (opt && opt.data) { this.setData(opt.data); } if (opt && opt.cause) { this.setCause(opt.cause); } if (opt && opt.source) { this.setSource(opt.source); } if (opt && opt.stack) { this.setStack(opt.stack); } Error.captureStackTrace(this, Exception); Object.setPrototypeOf(this, Exception.prototype); } setName(name) { this.name = name; return this; } setCode(code) { this.code = code; return this; } setMessage(msg) { this.message = msg; return this; } setData(data) { this.data = data; return this; } setCause(err) { this.cause = Exception.from(err).toPlan(); return this; } setSource(source) { this.source = source; return this; } setStack(stack) { this.stack = stack; return this; } // static __to_json_have_stack = false; toPlan() { let obj = { name: this.name, code: this.code, message: this.message, cause: this.cause, }; return obj; } toJSON() { return this.toPlan(); } static from(err, parser) { if (err instanceof Exception) { return err; } if (parser) { let e = parser.parse(err); if (e instanceof Exception) { return e; } } let e = Exception.parser.parse(err); if (e instanceof Exception) { return e; } return new Exception("Unknown error").setSource(err); } } exports.Exception = Exception; Exception.Authorization = "authorization"; Exception.Authentication = "authentication"; Exception.Notfound = "notfound"; Exception.Validation = "validation"; Exception.Unsupported = "unsupported"; Exception.Unavailable = "unavailable"; Exception.InternalServer = "internal-server"; Exception.Timeout = "timeout"; Exception.parser = new ExceptionParser();