簡體   English   中英

如何處理Promise鏈中的多個錯誤?

[英]How to handle multiple errors in promise chain?

我正在使用AWS Amplify進行身份驗證,並使用Stripe進行支付以創建注冊頁面。

問題:我找不到將對電子郵件和密碼部分(來自AWS Amplify)的驗證與付款信息部分(來自Stripe)的驗證相結合的方法。

我當前的代碼創建一個Stripe令牌並調用API(具有有效的付款信息),然后處理來自userSignupRequest的錯誤消息,該消息負責處理電子郵件和密碼字段。

如何驗證帶有付款信息的電子郵件和密碼,然后在AWS和Stripe中創建帳戶?

在此處輸入圖片說明

  // Stripe payment process
  this.props.stripe.createToken(
    {
      email: this.state.email
    }
  ).then(result => {
    // PROBLEM: Form server validation from Stripe
    if(result.error){
      return this.setState({ errors: { errorMsg: result.error.message }, isLoading: false })
    }

    // if success, create customer and subscription with result.token.id
    const apiName = 'NameOfAPI';
    const path = '/stripe/signup';
    let myInit = {
      body: {
        "stripeToken": result.token.id,
        "email": this.state.email
      }
    }

    API.post(apiName , path, myInit).then(reponse => {
      this.props.userSignupRequest(this.state.email, this.state.password, reponse).then(user => {
        this.setState({
          confirmAccount: true,
          isLoading: false,
          userEmail: this.state.email,
          errors: {}
        })
        this.props.history.push('/signup#confirm-account')
      }).catch(err => {
        // PROBLEM: Form server validation 
        this.setState({ errors: { errorMsg: err.message }, isLoading: false })
      })

    }).catch(err => {
      console.log(err)
      this.setState({ errors: { errorMsg: err }, isLoading: false })
    });

  })

看來我們有一個非常相似的堆棧。 我的解決方案是處理服務器端的所有內容。 您需要為lambda函數提供適當的IAM權限,以訪問Cognito。 下面的代碼有點長。 我使用async / await ,它確實為我清理了東西。 不過,您將需要在節點8上使用Lambda才能使用異步/等待。

我確認所有內容都與客戶端的正確格式匹配(即,電子郵件實際上是電子郵件,密碼是正確的長度)。 我意識到唯一可能出現的錯誤是Cognito的“現有用戶”錯誤。 這個想法是:在嘗試使用Stripe注冊該用戶之前,測試用戶是否存在。 無法使用“條紋”來“測試”用戶的信用卡是否有效。 全部或全無。 如果有效,它將通過,否則將出現錯誤。 如果通過,則可以使用Cognito對用戶進行注冊,知道您不會收到錯誤(您已經驗證了客戶端的電子郵件和密碼,並且知道該用途尚不存在)。

供參考,這是用於cognitoaws-sdk

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider({
  region: "region",
  userPoolId: "cognito_user_pool_id",
});

module.exports.signUpUser = (payload) => {
  const usernamePayload = {
    UserPoolId: "cognito_user_pool_id",
    Username: payload.email,
  };

  // I use emails for usernames.

    new Promise((resolve, reject) => {
      cognito.adminGetUser(usernamePayload, (error, response) => {
        if (error && error.code === 'UserNotFoundException') {
          resolve(false);
        } else if (error) {
          reject(error);
        } else {
          // if adminGetUser doesn't fail, it means the username exists
          resolve(true);
        }
      });
    }).then((usernameExists) => {
      if (!usernameExists) {
        // run stripe API stuff
        // always run before sign up below to catch stripe errors
        // and return those errors to client
        // before you sign up the user to Cognito

        // since you've already verified the user does not exist
        // it would be rare for an error to come up here
        // as long as you validate passwords and emails client-side
        const signUpPayload = {
          ClientId: "cognito_user_pool_client_id",
          Username: payload.email,
          Password: payload.password,
          UserAttributes: [
            {
              Name: 'email',
              Value: payload.email,
            },
          ],
        };

          new Promise((resolve, reject) => {
            cognito.signUp(signUpPayload, (error, response) => {
              if (error) {
                reject(error);
              } else {
                resolve(response);
              }
            });
          }).catch((error) => {
            // you should hopefully encounter no errors here
            // once you get everything setup correctly
            console.log(error);
          })
      } else {
        // means username already exists, send error to client
        // saying username exists
      }
    }).catch((error) => {
      // may want to dispatch this error to client
      console.log(error);
    });

  return null;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM