首页 文章

.catch()通过fetch()从另一个承诺中捕获所有错误

提问于
浏览
0

我创建了一个简单的函数来通过存储的令牌对用户进行身份验证,该函数基于一个promise,如果它已成功连接到我们的服务器API,则返回带有用户详细信息的响应,如果有服务器连接,它将返回promise promise由React-native fetch方法指定的错误 .

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.then(/***/) 内部出现错误时,它将被 AuthAPI.catch 捕获,但据我所知 AuthAPI.catch 将仅捕获来自该承诺拒绝的react-native fetch方法错误返回的错误 .

例如,在 AuthAPI.then 中,我已经为一个新的常量变量 const justAnotherVar = iamNotExist; 分配了一个未定义的变量,这样就会在下一个catch中抛出一个错误 .

ReferenceError: Can't find variable: iamNotExist

我想要的是保持 AuthAPI.catch 仅获取获取方法错误并在 AuthAPI.then(/***/) 内部出现错误时获得指定错误的常规红屏

1 回答

  • 0

    我相信这是打算发生的,在这里阅读更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

    您可以做的是添加一个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);
        });
    

相关问题