亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Catch 不捕獲錯誤?

為什么 Catch 不捕獲錯誤?

米脂 2022-01-07 16:50:02
當我執行函數“請求”提交一個 api 不會返回 200 的數字時,我會在應用程序中收到一個錯誤。為什么捕獲不捕獲錯誤?https://codeshare.io/5wWo9p
查看完整描述

3 回答

?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

從文檔中:


即使響應是 HTTP 404 或 500,從 fetch() 返回的 Promise也不會拒絕 HTTP 錯誤狀態。相反,它將正常解析(將 ok 狀態設置為 false),并且只會拒絕網絡故障或如果有任何事情阻止請求完成。


所以你應該檢查 response.ok:


fetch(request, { method: 'GET' }).then(response => {

  return response.ok

    ? response.json()

    : Promise.reject(new Error('Response not ok'));

});


查看完整回答
反對 回復 2022-01-07
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

看起來您在那里沒有任何嘗試語句來觸發捕獲。


你必須有類似的東西


try{

code to test

}

catch...


查看完整回答
反對 回復 2022-01-07
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

我推薦你,比如在整個請求函數中說@fab put try ... catch:


request(texto) {

  try{ // Added

    var request = "https://reqres.in/api/users/"+texto;

    fetch(request, {method: "GET"})

      .then((response) => {

        return response.json();

      })

      .then((responseJson) => {

        // Actualizar el state con la respuesta

        //console.log(this.error);

        this.setState({nombre:responseJson.data.first_name})

      })

      .catch((error) => {

        // Actualizar el state indicando que los datos son erróneos

        console.log(error);

        this.setState({nombre:error})

      }).done();

  }


  requestCrear(nombre) {

    var request = "https://reqres.in/api/users";

    t(request, {method: "POST", headers: {

        'Accept': 'application/json',

        'Content-Type': 'application/json',

      }, body: JSON.stringify({name: nombre})})

      .then((response) => {

        return response.json();

      })

      .then((responseJson) => {

        // Actualizar el state con la respuesta

        this.setState({nombre:responseJson.name})

      })

      .catch((error) => {

        // Actualizar el state indicando que los datos son erróneos

        this.setState({nombre:error})

      }).done();

  }


  render() {

    return (

      <View style={{ padding: 60}}>

        <TextInput

          style={{height: 40}}

          placeholder="Escribe un número para consultar"

          onSubmitEditing={

            (event) => {

              this.request(event.nativeEvent.text)

            }

          }

        />


        <TextInput

          style={{height: 40}}

          placeholder="Escribe un nombre para a?adir una persona"

          onSubmitEditing={

            (event) => {

              this.requestCrear(event.nativeEvent.text)

            }

          }

        />

        <Text style={{padding: 20, fontSize: 42}}>

          {this.state.nombre}

        </Text>

      </View>

    );

  }catch (e) { // Added

    console.log(e);

    // Here evaluate the error (e) ;

  }

}


查看完整回答
反對 回復 2022-01-07
  • 3 回答
  • 0 關注
  • 289 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號