koa.js 1.6 KB

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