user14451004
user14451004

Reputation:

How to throw exception inside promise?

There is a function that handles response from scan:

export const handleScanResponse = (
  scanResponse: IScanResponse,
  visitors: IVisitor[]
): Promise<IVisitor | any> => {
  return new Promise((resolve, reject) => {
    if (!scanResponse || scanResponse.errorDesc !== "SUCCESS")
      throw new Error("Scane response is empty!");

    const found = visitors.find((p: IVisitor) => {
      if (scanResponse && "qrcode" in scanResponse) {
        return (
          p.code && p.code.toLowerCase() === scanResponse.qrcode.toLowerCase()
        );
      } else {
        return (
          p.document_number &&
          scanResponse.document_number &&
          p.document_number.toLowerCase() ===
            scanResponse.document_number.toLowerCase()
        );
      }
    });

    if (found) resolve(found);

    reject(scanResponse);
  }).catch((e) => console.log(e));
};

I tried to resolve, reject in cases when user was found and not found in array. Otherwise try to throw an exeption.

Using is:

  handleScanResponse(
      scanerResponseMockup,
      this.visitorsService.visitors$.getValue()
    ).then(
      (foundVisitor) => this.visitorWasFound(foundVisitor),
      (scanResponse) => this.visitorNotFound(scanResponse)
    );

How to do that properly? Why despite exception I always go to .then( (foundVisitor) => this.visitorWasFound(foundVisitor)?

Upvotes: 2

Views: 93

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

When a .catch is added to the end of a Promise chain, and something throws, the whole Promise chain will resolve rather than reject. Your

.catch((e) => console.log(e));

is turning rejections into resolutions; the Promise that handleScanResponse returns will never reject.

Only catch errors at a place that you can handle them reasonably. Here, just leave out the .catch, and it should work as desired; this way, a rejected Promise will simply percolate up to the caller, and your

).then(
  (foundVisitor) => this.visitorWasFound(foundVisitor),
  (scanResponse) => this.visitorNotFound(scanResponse)
);

will be able to deal with it.

That said, there doesn't appear to be anything asynchronous going on in this code here. I'd recommend removing the Promise entirely.

Upvotes: 3

Related Questions