Advertisement
nubilfi

error-handling

Mar 28th, 2017
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const db = {
  2.     users: [
  3.         { name: 'John' },
  4.         { name: 'Jane' }
  5.     ]
  6. };
  7.  
  8. function users(req, res, next) {            // The users component will throw a notFoundError when a user doesn’t exist.
  9.     'use strict';
  10.     let match = req.url.match(/^\/user\/(.+)/);            // match the req.url using regexp
  11.  
  12.     console.log(db.users);      // [ { name: 'tobi' }, { name: 'loki' }, { name: 'jane' } ]
  13.     console.log(db.users[match[1]]);    // Why db.users[match[1]] always respond as 'undefined' ?
  14.  
  15.     if (match) {                            // check if the user index exists by using match[1]
  16.         //let user = db.users[match[1]];      // which is the first capture group
  17.         if (user) {                         // if the user exists, it's serialized as JSON
  18.             req.setHeader('Content-Type', 'application/json');
  19.             res.end(JSON.stringify(user));
  20.         } else {                            // otherwise an error is passed to the next() function
  21.             let err = new Error('User not found');      // with its notFound property set to true
  22.             err.notFound = true;
  23.             next(err);
  24.         }
  25.     } else {
  26.         next();
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement