UNPKG

mihawk

Version:

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

34 lines (33 loc) 1.37 kB
'use strict'; import Colors from 'color-cc'; import { readFileSync } from 'fs-extra'; import { Printer, Debugger } from '../utils/print'; import { ASSET_TPL_HTML_404_PATH, ASSET_TPL_HTML_50X_PATH } from '../root'; export default function error() { Debugger.log('mdw-err: init...'); const errHtml = readFileSync(ASSET_TPL_HTML_50X_PATH, 'utf-8'); const notFoundHtml = readFileSync(ASSET_TPL_HTML_404_PATH, 'utf-8'); return async function (ctx, next) { const { path, method } = ctx; const logPath = `${method} ${path}`; Debugger.log('mdw-err: >>'); try { await next(); } catch (err) { const { message, stack } = (err || {}); const errMsg = message || err?.toString() || 'Something wrong...'; Printer.error('MDW-err:', ctx.status, Colors.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); } } Debugger.log('mdw-err: <<', logPath); }; }