Почему не отрабатывает catch у внутреннего промиса?

Рейтинг: 0Ответов: 2Опубликовано: 19.07.2023

Подскажите пожалуйста, почему у внутреннего прописа не отрабатывает catch?

onFormSubmit = ({ email }: IFormValues) => {
    return new Promise<void>((resolve, reject) => {
      this.props
        .setProfile({ email })
        .then(() => {
          this.isEmailError = false;
          this.setProductSubscription(true)
            .then(() => resolve())
            .catch((errors: IError[]) => { // Вот этот catch 
              console.log('errors', errors) 
            });
        })
        .catch((errors: IError[]) => {
          return handleValidationErrors(errors);
        });
    })
  };

setProductSubscription = (isSubscribed: boolean) => {
    return this.props
      .setProductSubscription(this.props.productId, isSubscribed)
      .then(() => {
        if (isSubscribed && !this.state.isSidebarRendered) {
          Notification.success(createTranslatable('productSubscriptionSubscribedSuccessfully'));
        }
      })
      .catch((errors: IError[]) => {
        this.isEmailError = getValidationErrorByCode(errors, ERROR_CODE_NO_EMAIL)?.code === ERROR_CODE_NO_EMAIL;

        if (this.isEmailError) {
          return this.renderSidebar();
        }

        showValidationErrors(errors);
      });
  };

Ответы

▲ 1Принят

Потому что у вас ошибку уже обработал вот этот catch:

.catch((errors: IError[]) => {
    this.isEmailError = getValidationErrorByCode(errors, ERROR_CODE_NO_EMAIL)?.code === ERROR_CODE_NO_EMAIL;

    if (this.isEmailError) {
        return this.renderSidebar();
    }

    showValidationErrors(errors);
});

Чтобы тот catch срабатывал, можно обернуть тело setProductSubscription в промис:

setProductSubscription = (isSubscribed: boolean) => {
    return new Promise<void>((res, rej) => {
        this.props
            .setProductSubscription(this.props.productId, isSubscribed)
            .then(() => {
                if (isSubscribed && !this.state.isSidebarRendered) {
                    Notification.success(createTranslatable('productSubscriptionSubscribedSuccessfully'));
                }
                res();
            })
            .catch((errors: IError[]) => {
                this.isEmailError = getValidationErrorByCode(errors, ERROR_CODE_NO_EMAIL)?.code === ERROR_CODE_NO_EMAIL;
    
                if (this.isEmailError) {
                    this.renderSidebar();
                    rej(errors);
                    return;
                }
    
                showValidationErrors(errors);
                rej(errors);
            });
    })
};
▲ 0

catch выполнится если промис закончится ошибкой