koa.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. footer: 'Hello <strong>World</strong>',
  11. error: 'Error %code%',
  12. page_title: "We've got some trouble | %code% - %title%",
  13. }));
  14. // demo handler
  15. _webapp.use(async (ctx, next) => {
  16. if (ctx.path == '/'){
  17. ctx.type = 'text';
  18. ctx.body = 'HttpErrorPages Demo';
  19. }else{
  20. return next();
  21. }
  22. });
  23. // throw an 403 error
  24. _webapp.use(async (ctx, next) => {
  25. if (ctx.path == '/my403error'){
  26. ctx.throw(403);
  27. }else{
  28. return next();
  29. }
  30. });
  31. // throw an 533 error with status 500
  32. _webapp.use(async (ctx, next) => {
  33. if (ctx.path == '/x533'){
  34. const e = new Error("custom");
  35. e.errorpage = '533';
  36. e.status = 500;
  37. throw e;
  38. }else{
  39. return next();
  40. }
  41. });
  42. // throw an internal error
  43. _webapp.use(async (ctx, next) => {
  44. if (ctx.path == '/500'){
  45. throw new Error('Server Error');
  46. }else{
  47. return next();
  48. }
  49. });
  50. // start service
  51. _webapp.listen(8888);
  52. }
  53. // invoke bootstrap operation
  54. bootstrap()
  55. .then(function(){
  56. console.log('Running Demo on Port 8888');
  57. })
  58. .catch(function(e){
  59. console.error(e);
  60. });