express.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const _render = require('./page-renderer');
  2. const _parseOptions = require('./options');
  3. const _getResources = require('./resources');
  4. const _dispatch = require('./dispatcher');
  5. // wrapper to add custom options
  6. async function createDispatcher(options={}){
  7. // merge options
  8. const opt = _parseOptions(options);
  9. // load resources
  10. const resources = await _getResources(opt);
  11. // multi-type support
  12. // @see https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
  13. return function dispatchRequest(page, httpStatusCode, req, res, err){
  14. // run generic dispatcher
  15. const {pageData, templateVars} = _dispatch(opt, resources, page, httpStatusCode, err);
  16. // set http status code
  17. res.status(httpStatusCode || 500);
  18. // multiple response formats
  19. res.format({
  20. // standard http-error-pages
  21. html: function(){
  22. res.type('.html');
  23. res.send(_render(resources.template, resources.stylesheet, opt.filter(templateVars)))
  24. },
  25. // json
  26. json: function(){
  27. res.json({
  28. error: `${pageData.title} - ${pageData.message}`
  29. })
  30. },
  31. // text response
  32. default: function(){
  33. // plain text
  34. res.type('.txt').send(`${pageData.title} - ${pageData.message}`);
  35. }
  36. })
  37. }
  38. }
  39. module.exports = async function httpErrorPages(router, options={}){
  40. // create new disptacher with given options
  41. const dispatch = await createDispatcher(options);
  42. // default 404 error - no route matches
  43. router.all('*', function(req, res){
  44. dispatch('404', 404, req, res, new Error('file not found'));
  45. });
  46. // internal errors (all)
  47. router.use(function(err, req, res, next){
  48. // status code given ?
  49. if (err.status){
  50. // custom errorpage set ?
  51. dispatch(err.errorpage || err.status, err.status, req, res, err);
  52. // use default http500 page
  53. }else{
  54. dispatch('500', 500, req, res, err);
  55. }
  56. });
  57. };