neura-express-app
Version:
Basic express application starter with some common utilities.
73 lines (72 loc) • 2.67 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NeuraErrorHandler = void 0;
const util_1 = __importDefault(require("util"));
const app_error_1 = require("../errors/app.error");
class NeuraErrorHandler {
constructor(logger) {
this.logger = logger;
this.listenNativeEvents();
}
onClose(cb) {
this.onCloseCb = cb;
}
async handleError(error) {
try {
const appError = this.normalizeError(error);
this.logger.error(`ErrorHandler: Application error`, appError);
if (!appError.isTrusted) {
await this.closeApp();
}
}
catch (handlingError) {
process.stderr.write(`Failed to handle error properly!`);
process.stderr.write(JSON.stringify(error));
process.stderr.write(JSON.stringify(handlingError));
}
}
listenNativeEvents() {
process.on("uncaughtException", async (error) => {
await this.handleError(error);
});
process.on("unhandledRejection", async (error) => {
await this.handleError(error);
});
process.on("SIGTERM", async () => {
this.logger.info(`SIGTERM signal received, trying to close app gracefully!`);
await this.closeApp();
});
process.on("SIGINT", async () => {
this.logger.info(`SIGINT signal received, trying to close app gracefully!`);
await this.closeApp();
});
}
async closeApp() {
try {
if (this.onCloseCb) {
await this.onCloseCb();
}
process.exit(0);
}
catch (err) {
this.logger.error("ErrorHandler: Error while exiting process", err);
process.exit(1);
}
}
normalizeError(errorToHandle) {
if (errorToHandle instanceof app_error_1.NeuraAppError) {
return errorToHandle;
}
if (errorToHandle instanceof Error) {
const appError = new app_error_1.NeuraAppError(errorToHandle.name, errorToHandle.message, false, errorToHandle?.stack);
appError.stack = errorToHandle.stack;
return appError;
}
const inputType = typeof errorToHandle;
return new app_error_1.NeuraAppError("unknown-error", `Error handler receives an error of type - ${inputType}, value ${util_1.default.inspect(errorToHandle)}`);
}
}
exports.NeuraErrorHandler = NeuraErrorHandler;