简体   繁体   English

在本机反应中强制捕获尝试错误响应?

[英]force catch on try error response in react native?

the api i am using returns an error that is 200 status:我正在使用的 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 [];
    });
}

i want data.Error passed on catch e value?我想要通过 catch e 值传递的 data.Error 吗? but the problem in react native is it crash, i want to show the error message text?但是 react native 的问题是它崩溃了,我想显示错误消息文本?

I have no proof of that but I don't think raising or throwing an exception inside a success callback is recommended.我没有证据证明这一点,但我认为不建议在成功回调中引发或抛出异常。 I would suggest to return promises instead and handling callbacks outside your searchCharacters() function using async/await我建议改为返回承诺并使用 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native中的响应错误 - Response error in React Native SSJS Platform.Response.Redirect 在 Try Catch 语句中引发错误 - SSJS Platform.Response.Redirect throws error in Try Catch Statement 捕获错误 JSON 解析错误:无法识别的令牌&#39;&lt;&#39; - react-native - Catch Error JSON Parse Error: Unrecognized token'<' - react-native 如何强制 mongodb 错误以开玩笑的方式测试 try and catch 条件 - How can I force a mongodb error to test with jest the try and catch condition React Native获取有时会捕获JSON解析错误 - React Native fetch sometimes catch a JSON parse error 在捕获错误处理程序中反应本机显示对话框或弹出窗口 - React Native show Dialog or Popup in catch error handler 反应本机导航错误-TypeError:无法读取未定义的属性'catch' - React native navigation error -TypeError: Cannot read property 'catch' of undefined React Native - 未处理的 Promise 拒绝 - 在哪里捕获错误? - React Native - Unhandlled Promise Rejection - where to catch the error? 爱讯。 即使api返回404错误,如何在try catch finally中获得错误响应 - Axios. How to get error response even when api return 404 error, in try catch finally 如何使用try catch捕获回调错误? - How to catch a callback error with a try catch?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM