力赶上反应本机尝试错误响应?

时间:2020-03-05 13:59:25

标签: javascript react-native

我正在使用的api返回200状态错误:

function searchCharacters(text: string, page: number) {
  return axios
    .get('http://www.omdbapi.com/', {
      params: {
        apiKey,
        s: text,
        page,
      },
    })
    .then(({data}) => {
      if (data.Error) {
        return data.Error;
      }
      return data.Search;
    })
    .catch(e => {
      console.error(e);
      return [];
    });
}

我要数据。catch e值传递错误?但是react native的问题是它崩溃了,我想显示错误消息文本吗?

1 个答案:

答案 0 :(得分:0)

我没有任何证据,但是我不建议在成功回调中引发或引发异常。我建议改为返回promise,并使用async / await处理您searchCharacters()函数外部的回调

async function searchCharacters(text: string, page: number) {
  return axios
    .get('http://www.omdbapi.com/', {
      params: {
        apiKey,
        s: text,
        page,
      },
    })
    .then(({data}) => {
      if (data.Error) {
        return Promise.reject(data.Error);
      }
      return Promise.resolve(data.Search);
    })
    .catch(e => {
      return Promise.reject(e)
    });
}


// you could call your `searchCharacters()` like this

const Search = await searchCharacters('hello', 2).catch(error =>{
    console.log('an error has occurred', error);
    // maybe set your list to an empty list here
})

if(Search) {
   console.log('success', Search);
   // maybe set your list to the search result here
}