UNPKG

mihawk

Version:

A tiny & simple mock server tool, support json,js,cjs,ts(typescript).

50 lines (49 loc) 2.52 kB
'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const color_cc_1 = __importDefault(require("color-cc")); const fs_extra_1 = require("fs-extra"); const print_1 = require("../utils/print"); const root_1 = require("../root"); function error() { print_1.Debugger.log('mdw-err: init...'); const errHtml = (0, fs_extra_1.readFileSync)(root_1.ASSET_TPL_HTML_50X_PATH, 'utf-8'); const notFoundHtml = (0, fs_extra_1.readFileSync)(root_1.ASSET_TPL_HTML_404_PATH, 'utf-8'); return function (ctx, next) { return __awaiter(this, void 0, void 0, function* () { const { path, method } = ctx; const logPath = `${method} ${path}`; print_1.Debugger.log('mdw-err: >>'); try { yield next(); } catch (err) { const { message, stack } = (err || {}); const errMsg = message || (err === null || err === void 0 ? void 0 : err.toString()) || 'Something wrong...'; print_1.Printer.error('MDW-err:', ctx.status, color_cc_1.default.red(`Occurs error: ${errMsg}\n`), err); console.log(); ctx.set('Content-Type', 'text/html'); if (ctx.status === 404) { ctx.body = notFoundHtml.replace('<%= detailMsg %>', `${errMsg}(<em>${logPath}</em> is not found!)`); } else { ctx.status = 500; ctx.body = errHtml.replace('<%= errMsg %>', errMsg).replace('<%= errStack %>', stack); } } print_1.Debugger.log('mdw-err: <<', logPath); }); }; } exports.default = error;