koa.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const _koa = require('koa');
  2. const _webapp = new _koa();
  3. // use require('http-error-pages') for regular apps!
  4. const _httpErrorPages = require('../lib/main');
  5. async function bootstrap(){
  6. // use http error pages handler (INITIAL statement!)
  7. // because of the asynchronous file-loaders, wait until it has been executed - it returns an async handler
  8. _webapp.use(await _httpErrorPages.koa({
  9. lang: 'en_US',
  10. payload: {
  11. footer: 'Hello <strong>World</strong>',
  12. pagetitle: 'we are sorry - an internal error encountered',
  13. },
  14. filter: function(data, ctx){
  15. // remove footer
  16. //data.footer = null;
  17. return data;
  18. },
  19. onError: function(data){
  20. // for debugging purpose only!!
  21. // use custom middleware for errorlogging!!
  22. console.log(`[koa] ERROR: ${data.title}\n${data.error.stack}`)
  23. }
  24. }));
  25. // demo handler
  26. _webapp.use(async (ctx, next) => {
  27. if (ctx.path == '/'){
  28. ctx.type = 'text';
  29. ctx.body = 'HttpErrorPages Demo';
  30. }else{
  31. return next();
  32. }
  33. });
  34. // throw an 403 error
  35. _webapp.use(async (ctx, next) => {
  36. if (ctx.path == '/my403error'){
  37. ctx.throw(403);
  38. }else{
  39. return next();
  40. }
  41. });
  42. // throw an 533 error with status 500
  43. _webapp.use(async (ctx, next) => {
  44. if (ctx.path == '/x533'){
  45. const e = new Error("custom");
  46. e.errorpage = '533';
  47. e.status = 500;
  48. throw e;
  49. }else{
  50. return next();
  51. }
  52. });
  53. // throw an internal error
  54. _webapp.use(async (ctx, next) => {
  55. if (ctx.path == '/500'){
  56. throw new Error('Server Error');
  57. }else{
  58. return next();
  59. }
  60. });
  61. // start service
  62. _webapp.listen(8888);
  63. }
  64. // invoke bootstrap operation
  65. bootstrap()
  66. .then(function(){
  67. console.log('Running Demo on Port 8888');
  68. })
  69. .catch(function(e){
  70. console.error(e);
  71. });