Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react native中强制捕获try错误响应?_Javascript_React Native - Fatal编程技术网

Javascript 在react native中强制捕获try错误响应?

Javascript 在react native中强制捕获try错误响应?,javascript,react-native,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.

我使用的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 [];
    });
}

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

我没有证据证明这一点,但我认为不建议在成功回调中引发或抛出异常。我建议使用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
}