UNPKG

kopi-error-handler

Version:

This library is used to save time for reimplementing express not found and error handler, along with a nice and pretty method to return an error response with a proper error structure.

1 lines 2.21 kB
"use strict";function asyncGeneratorStep(a,b,c,d,e,f,g){try{var h=a[f](g),i=h.value}catch(a){return void c(a)}h.done?b(i):Promise.resolve(i).then(d,e)}function _asyncToGenerator(a){return function(){var b=this,c=arguments;return new Promise(function(d,e){function f(a){asyncGeneratorStep(h,d,e,f,g,"next",a)}function g(a){asyncGeneratorStep(h,d,e,f,g,"throw",a)}var h=a.apply(b,c);f(void 0)})}}var httpErrorCreator=require("./httpErrorCreator"),_require=require("kopitech-logger")("Exception Handler"),L=_require.L,logNotFoundRoute="true"===(process.env.ERROR_HANDLER_LOG_NOT_FOUND_ROUTE||"false"),logError="true"===(process.env.ERROR_HANDLER_LOG_ERROR||"false"),handleNotFound=/*#__PURE__*/function(){var a=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function a(b,c,d){var e,f,g,h,i;return regeneratorRuntime.wrap(function(a){for(;;)switch(a.prev=a.next){case 0:try{logNotFoundRoute&&(e=b.originalUrl.indexOf("?"),f=0<=e,g=f?b.originalUrl.slice(0,e):b.originalUrl,L.info("Not Found for Route \"".concat(g,"\""))),h=httpErrorCreator.create({code:404,stackTrace:!1}),d(h)}catch(a){i=httpErrorCreator.create({data:a}),logError&&L.error("Error in not found handling, wrapping in generic error"),d(i)}case 1:case"end":return a.stop();}},a)}));return function(){return a.apply(this,arguments)}}(),handleError=/*#__PURE__*/function(){var a=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function a(b,c,d){var e,f,g,h,i,j,k,l;return regeneratorRuntime.wrap(function(a){for(;;)switch(a.prev=a.next){case 0:try{e=b,e.response?(f=e.response,g=f.status,h=f.data,e=httpErrorCreator.create({code:g,data:h})):"ValidationError"===e.name&&(i=e,j=i.status,k=i.message,e=httpErrorCreator.create({code:j,message:k,data:e})),e.isKopiHttpError||(e=httpErrorCreator.create({data:e})),logError&&L.error(JSON.parse(JSON.stringify(e))),d.status(e.code).json(e.data)}catch(a){l=httpErrorCreator.create({data:a}),logError&&(L.error("Error in error handling, wrapping in generic error"),L.error(JSON.parse(JSON.stringify(l)))),d.status(l.code).json(l.data)}case 1:case"end":return a.stop();}},a)}));return function(){return a.apply(this,arguments)}}();module.exports={handleNotFound:handleNotFound,handleError:handleError};