繁体   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