Advertisement
nubilfi

error-handling example

Mar 28th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const connect = require('connect');
  2.  
  3. function hello(req, res, next) {
  4.     'use strict';
  5.     if (req.url.match(/^\/hello/)) {    // match '/hello' with regexp
  6.         res.end('Hello World\n');
  7.     } else {
  8.         next();
  9.     }
  10. }
  11.  
  12. const db = {
  13.     users: [
  14.         { name: 'John' },
  15.         { name: 'Jane' }
  16.     ]
  17. };
  18.  
  19. function users(req, res, next) {            // The users component will throw a notFoundError when a user doesn’t exist.
  20.     'use strict';
  21.     let match = req.url.match(/^\/user\/(.+)/);            // match the req.url using regexp
  22.     if (match) {                            // check if the user index exists by using match[1]
  23.         let user = db.users[match[1]];      // which is the first capture group
  24.         if (user) {                         // if the user exists, it's serialized as JSON
  25.             req.setHeader('Content-Type', 'application/json');
  26.             res.end(JSON.stringify(user));
  27.         } else {                            // otherwise an error is passed to the next() function
  28.             let err = new Error('User not found');      // with its notFound property set to true
  29.             err.notFound = true;
  30.             next(err);
  31.         }
  32.     } else {
  33.         next();
  34.     }
  35. }
  36.  
  37. function pets(req, res, next) {     //The pets component will cause a ReferenceError to be thrown to demonstrate the error handler.
  38.     'use strict';
  39.     if (req.url.match(/^\/pet\/(.+)/)) {
  40.         foo();      // trigger an exception by called undefined foo() function
  41.     } else {
  42.         next();
  43.     }
  44. }
  45.  
  46. function errorHandler(err, req, res, next) {        // The errorHandler component will handle any errors from the api app.
  47.     'use strict';
  48.     // an error-handling that doesn't expose unecessary data
  49.     console.error(err.stack);
  50.     res.setHeader('Content-Type', 'application/json');
  51.     if (err.notFound) {
  52.         res.statusCode = 404;
  53.         res.end(JSON.stringify({ error: err.message }));
  54.     } else {
  55.         res.statusCode = 500;
  56.         res.end(JSON.stringify({ error: 'Internal server error' }));
  57.     }
  58. }
  59.  
  60. const api = connect()
  61.     .use(users)
  62.     .use(pets)
  63.     .use(errorHandler);
  64.  
  65. const app = connect()
  66.     .use(hello)
  67.     .use('/api', api)
  68.     .listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement