express.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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, req, res)))
  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. // eslint-disable-next-line no-unused-vars
  48. router.use(function(err, req, res, next){
  49. // status code given ?
  50. if (err.status){
  51. // custom errorpage set ?
  52. dispatch(err.errorpage || err.status, err.status, req, res, err);
  53. // use default http500 page
  54. }else{
  55. dispatch('500', 500, req, res, err);
  56. }
  57. });
  58. };