前端请求接口错误处理

523 阅读1分钟

new XMLHttpRequest()请求中做了state数据处理,此时需要code!=100情况下抛出throw res,如下代码:

 xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
      if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
        resolve(JSON.parse(xhr.responseText))
        }else{
            reject(JSON.parse(xhr.responseText))
        }
    }
}
 if (this.state.stop) {
      this.setState({
        stop: false
     },()=>{
        (id ? addOrUpdateWelcome(data) : addOrUpdateWelcome(data)).then(res => {
            if (res.code == 100) {
              message.success(id ? '修改成功' : '创建成功')
            } else {
              throw res
            }
        }).catch(req => {
            this.setState({
              stop: true
            })
            message.error(req.msg ? req.msg : '服务器错误,请稍后重试')
        })
    })
 }

接口返回code==100时,才是正确返回参数,如下是在new XMLHttpRequest()请求中做了code的校验: