UNPKG

@kitmi/jacaranda

Version:

JavaScript application framework

67 lines (66 loc) 2.17 kB
/** * Error response middleware with json * @module Middleware_JsonError */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function() { return _default; } }); const _nodehttp = /*#__PURE__*/ _interop_require_default(require("node:http")); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Wrap the error response into json format and with the apiWrapper service if exists. * @param {*} opt * @param {*} app * @returns {Function} Middleware function */ const jsonError = (opt, app)=>{ const apiWrapper = app.getService(app.settings?.apiWrapperService || 'apiWrapper'); const handler = apiWrapper && apiWrapper.wrapError; return async (ctx, next)=>{ try { await next(); if (ctx.errorHandled) { return; } if (ctx.status >= 400) { if (ctx.type === 'text/plain') { ctx.throw(ctx.status, ctx.body); } else { ctx.throw(ctx.status); } } } catch (err) { ctx.status = typeof err.status === 'number' && err.status >= 100 ? err.status : 500; ctx.type = 'application/json'; let errReport = err; // accepted types if (handler) { try { // avoid error in error handling ctx.body = handler(ctx, err); ctx.app.emit('error', err, ctx); ctx.errorHandled = true; return; } catch (error) { error.innerError = err; errReport = error; } } ctx.body = { error: errReport.expose && errReport.message ? errReport.message : _nodehttp.default.STATUS_CODES[ctx.status] }; ctx.app.emit('error', errReport, ctx); } }; }; const _default = jsonError; //# sourceMappingURL=jsonError.js.map