[英]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.