Node JS crash on throwing exception inside .then inside try{} with catch{}

90 Views Asked by At

The code is greatly simplified.
I have an express router handler.

 confirmLoginWithCode(req, res, next) {
   try {
      if (isCodeExpired) {
*       throw ApiError.BadResultField('SMS code expired');
      }

      gtPostRequestWithXMLParsing(requestBody)
        .then((resultMessage)=>{
***       throw ApiError.BadResultField(resultMessage)
        })

    } catch (e) {
*****   next(e);
    }
  };
}

exception from * works perfectly. But exception from *** crashes the NodeJS. It seems strange to me, because it is inside try-catch block and it should be catched by *****. Why this happens and how to handle it?

1

There are 1 best solutions below

0
Andrej Denisov On

I found the problem. throw inside .then will work in its own context out of outer try-catch block and should be handled separately, so I just added .catch after then (*******)

                .then((resultMessage)=>{
                  throw ApiError.BadResultField(resultMessage)
                })
*******         .catch((e => next(e)))