Guest User

Untitled

a guest
Jul 17th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. const express = require('express');
  2. const app = express();
  3.  
  4. app.use(async(req, res, next) => {
  5. await authenticate(req);
  6. next();
  7. });
  8.  
  9. app.get('/route', async(req, res) => {
  10. const result = await request('http://example.com');
  11. res.end(result);
  12. });
  13.  
  14. app.use((err, req, res, next) => {
  15.  
  16. console.error(err);
  17.  
  18. res
  19. .status(500)
  20. .end('error');
  21. })
  22.  
  23. app.listen(8080);
  24.  
  25. app.get('/route', (req, res, next) => {
  26. throw new Error('Error');
  27. res.end(result);
  28. });
  29.  
  30. Layer.prototype.handle_request = function handle(req, res, next) {
  31. var fn = this.handle;
  32.  
  33. if (fn.length > 3) {
  34. // not a standard request handler
  35. return next();
  36. }
  37.  
  38. try {
  39. fn(req, res, next);
  40. } catch (err) {
  41. next(err);
  42. }
  43. };
  44.  
  45. app.get('/route', async(req, res, next) => {
  46. try {
  47. const result = await request('http://example.com');
  48. res.end(result);
  49. } catch(err) {
  50. next(err);
  51. }
  52. });
  53.  
  54. const asyncHandler = fn => (req, res, next) => {
  55. return Promise
  56. .resolve(fn(req, res, next))
  57. .catch(next);
  58. };
  59.  
  60. module.exports = asyncHandler;
  61.  
  62. app.use(asyncHandler(async(req, res, next) => {
  63. await authenticate(req);
  64. next();
  65. }));
  66.  
  67. app.get('/async', asyncHandler(async(req, res, next) => {
  68. const result = await request('http://example.com');
  69. res.end(result);
  70. }));
  71.  
  72. // Any rejection will go to the error handler
Add Comment
Please, Sign In to add comment