Javascript .catch()正在通过fetch()捕获所有错误,即使来自另一个承诺
我创建了一个简单的函数,通过用户存储的令牌对用户进行身份验证,该函数基于一个承诺,如果成功连接到我们的服务器API,它将返回一个带有用户详细信息的响应,如果存在服务器连接,它将通过React native fetch方法返回一个带有指定错误的承诺拒绝Javascript .catch()正在通过fetch()捕获所有错误,即使来自另一个承诺,javascript,react-native,promise,Javascript,React Native,Promise,我创建了一个简单的函数,通过用户存储的令牌对用户进行身份验证,该函数基于一个承诺,如果成功连接到我们的服务器API,它将返回一个带有用户详细信息的响应,如果存在服务器连接,它将通过React native fetch方法返回一个带有指定错误的承诺拒绝 import React, { Component } from 'react'; import { Text, View, AlertIOS, } from 'react-native'; function AuthAP
import React, { Component } from 'react';
import {
Text,
View,
AlertIOS,
} from 'react-native';
function AuthAPI(token)
{
return new Promise((resolve, reject) => {
fetch("https://myawesomeapi.com/auth", {
method: "POST",
body: '{"token": "' + token + '"}',
})
.then((response) => response.json())
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
}
export default class Home extends Component
{
constructor(props)
{
super(props);
this.state = {
bodyMessage: 'Waiting for response!',
};
}
componentWillMount()
{
AuthAPI("token-here")
.then((response) => {
const justAnotherVar = iamNotExist; // this will throw an error in next .catch
AlertIOS.alert("Your Name: " + response.userFullName);
this.setState({bodyMessage: 'Fetch is done with a response!'});
})
.catch((error) => {
console.err(error);
});
}
render()
{
const { bodyMessage } = this.state;
return (
<View style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Welcome..</Text>
<Text>{bodyMessage}</Text>
</View>
);
}
}
我想要的是保持
AuthAPI.catch
getting fetch method errors only,并在AuthAPI内部出现错误时获得带有指定错误的常规红屏。然后(/***/)
我相信这是有意的,请在此处阅读更多内容:
您可以添加一个try/catch,使.then语句具有自己的错误处理,并且在出现问题时不会触发.catch:
AuthAPI("token-here")
.then((response) => {
try {
const justAnotherVar = iamNotExist; // this will throw an error in next .catch
AlertIOS.alert("Your Name: " + response.userFullName);
this.setState({bodyMessage: 'Fetch is done with a response!'});
} catch (e) {
//error handling
}
})
.catch((error) => {
console.err(error);
});
您可以检查捕获中的错误是否是ApiError的实例,否则抛出剩余的错误谢谢@ShubhamKhatri,只是您的评论有点不可理解。。Matt Aft的答案非常适合我的情况
AuthAPI("token-here")
.then((response) => {
try {
const justAnotherVar = iamNotExist; // this will throw an error in next .catch
AlertIOS.alert("Your Name: " + response.userFullName);
this.setState({bodyMessage: 'Fetch is done with a response!'});
} catch (e) {
//error handling
}
})
.catch((error) => {
console.err(error);
});