new to express & js and trying to understand next

32 views Asked by At

This is new to me and Im trying to learn so my terminology and code may be not be the best :).

I have code like below. createCustomer adds row to a table. My intention is if missing data then dont call the db function.

    try {
      if (!username || 
        !password || 
        !email || 
        !firstname || 
        !lastname || 
        !phone_number||
        !role) {
        next({
          name: "MissingCustomerDataError",
          message: "Required Field - username, password, email, firstname, lastname, phone_number"
        });
        // throw new RouteError({
        //     name: "MissingCustomerDataError",
        //     message: "Required Field - username, password, email, firstname, lastname, phone_number"
        //   });
      }
   ...(some more code)
      const cust = await createCustomer({ 
        username, 
        password, 
        email, 
        firstname, 
        lastname, 
        phone_number, 
        role, 
        address });

I would expect next(...) to "next" out of this logic and onto my error handler which I have attached after this route, but it still calls the db function. If I use throw it does seem to get out of this logic and into the catch block. Shouldnt next also leave this try block and move on? I think Im missing something conceptually. Thanks

1

There are 1 answers

1
jabaa On BEST ANSWER

Your expectation is wrong. A call of next starts the next middleware/request handler. It doesn't stop the current function. You can stop and leave a function with a return statement, e.g.:

if (!username || 
    !password || 
    !email || 
    !firstname || 
    !lastname || 
    !phone_number||
    !role) {
    return next({
      name: "MissingCustomerDataError",
      message: "Required Field - username, password, email, firstname, lastname, phone_number"
    });

or handle the error using a throw statement.