微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从路由器'获取' - 如何将'res.status(400).json('Enter failure message here')'作为.then .catch中的错误处理?

如何解决从路由器'获取' - 如何将'res.status(400).json('Enter failure message here')'作为.then .catch中的错误处理?

我将以下代码作为我的 React Native 组件之一中的 Button 的一部分。观察如何没有 .catch 来处理来自服务器的可能的“无结果”情况;它是用 if 语句处理的(例如:else if (acceptMatchRequestData['status']==='failure') 我正试图摆脱它。

                  await acceptMatchRequest(match['matchId'],userId,getUserInfoData[0]['ratings'][matchType])
                  .then(acceptMatchRequestData => {
                    if (acceptMatchRequestData['status']==='success') {
                      setMatchInvites(prevstate => {
                        return prevstate.filter((observation,i) => observation['matchId'] !== match['matchId'])
                      })
                      setMatchScreenParentState('loading')
                      sendToUserDeviceNotification('matchFound',match['matchedUserId'])
                    } else if (acceptMatchRequestData['status']==='failure') {
                      Alert.alert('',acceptMatchRequestData['message'])
                    }
                  })

acceptMatchRequest 函数代码

export async function acceptMatchRequest(matchId,rating) {
  console.log('Attempting to accept match request');

  info = { matchId,rating }

  const firebaseIdToken = await AsyncStorage.getItem('@firebaseIdToken')
  const requestOptions = {
      method: 'POST',headers: { 'Content-Type': 'application/json','Authorization': 'Bearer ' + firebaseIdToken },body: JSON.stringify(info)
  };
  const response = await fetch(ngrokOrLocalhost + '/acceptmatchrequest',requestOptions)
  const data = await response.json()
  return data
}

和服务器代码

router.post('/acceptmatchrequest',async (req,res) => {
  const { matchId,rating } = req.body;
    
  const results = await Match.find({ 'usersInfo.userId': userId,'matchRecords.matchConfirmed': { $nin: [true] } }).limit(5)

  if (results.length===5) {
    res.status(400).json({'status': 'failure','message': 'You already have 5 active matches. Please finish a match first before you can accept this match.'})
  } else {
    var filter2 = { '_id': matchId }
    var update2 = { 'isCustomrequest_IsAccepted': true,'$push': { 'usersInfo': { 'userId': userId,'location': { 'type': 'Point','coordinates': [0,0] },'rating': rating } } }
    var response2 = await Match.findOneAndUpdate(filter2,update2,{ new: true,sort: { 'matchCreatedTimestamp': 1 } })

    if (response2) {
      // Document was updated
      res.status(200).json({'status': 'success','message': 'Match request was accepted successfully'})
    } else {
      console.log('Match request was not accepted successfully');
      res.status(400).json({'status': 'failure','message': 'Match request was not accepted successfully'})
    }
  }
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。