【问题标题】:How to catch the network error while fetching the error in promise如何在获取承诺中的错误时捕获网络错误
【发布时间】:2016-12-20 03:38:28
【问题描述】:

所以我有这个 Picker 组件,对于项目,我从服务器获取数据并在状态更改时映射它。

//api.js
var api = {
    getBooks() {
        var url = 'http://192.168.43.14:8080/api/books/'
        var headers = new Headers();
        headers.append('Accept', 'application/json');
        return fetch(url, headers)
            .then((res) => res.json())  
            .catch(function(err) {  
                console.log('Fetch Error :-S', err);
                throw Error(err);
            });
    }
}

//RegisterMobile.js
import api from '../utilities/api'

export default class RegisterMobile extends Component {
    constructor(props) {
        super(props)
        this.state = {
            books: [],
            book: '',
            mobile: '',
            displayError: false,
            error: 'Please provide a valid mobile number'
        }
    }

    componentWillMount() {
        api.getBooks().then((res) => {
            this.setState({
                books: res
            })
        })
    }

    render() {
        return(
            <View>
                <View style={styles.selecBook}>
                    <Picker selectedValue={this.state.book} onValueChange={this.changeBook}>
                        {this.state.books.map((book) => {return <Picker.Item value={book.name} label={book.name} key={book.id}  />})}
                    </Picker>
                </View>
                {this.state.displayError ? <Text style={styles.error}>{this.state.error}</Text> : null}
            </View>
        )
    }
}

这工作正常。我得到了项目列表,当我点击 Picker 时,我可以选择项目。我想要做的是,如果在获取数据时出现任何错误(例如服务器已关闭),我想获取该错误并将其显示为错误(这将只是更改 error 和 @ 987654323@)。但是如果有一个将其设置为错误状态,我不知道如何获取错误。

【问题讨论】:

  • api.getBooks().then((res) =&gt; { this.setState({ books: res }).catch(e =&gt; this.setState({ displayError: true } )?
  • @guest271314 嗨!我试过你的方法,但它给了我这个错误:Possible Unhandled Promise Rejection (id: 0): this.setState is not a function TypeError: this.setState is not a function
  • 呃,你已经证明你知道如何在你的 API 中catch(并重新抛出)错误,那么为什么它在组件中会有任何不同(除此之外你不会重新扔在那里)?

标签: javascript react-native es6-promise fetch-api


【解决方案1】:
componentWillMount() {
    api.getBooks()
       .then((res) => { this.setState({books: res}) })
       .catch(function(err) {  
            if (err.message === 'Network Error') {
                // This is a network error.
            }
        });
}

【讨论】:

    【解决方案2】:

    不要在 api 中捕获错误。在要使用异步操作结果的地方执行此操作。像这样的...

    //api.js
    var api = {
        getBooks() {
            var url = 'http://192.168.43.14:8080/api/books/'
            var headers = new Headers();
            headers.append('Accept', 'application/json');
            return fetch(url, headers)
                .then((res) => res.json());
    
        }
    }
    
    //RegisterMobile.js
    import api from '../utilities/api'
    
    export default class RegisterMobile extends Component {
        constructor(props) {
            super(props)
            this.state = {
                books: [],
                book: '',
                mobile: '',
                displayError: false,
                error: 'Please provide a valid mobile number'
            }
        }
    
        componentWillMount() {
            api.getBooks()
               .then((res) => { this.setState({books: res}) })
               .catch(function(err) {  
                    console.log('Fetch Error :-S', err);
                    this.setState({books: [], book: null, displayError: true, error:err});
                });
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2022-12-19
    • 2021-03-03
    • 2021-02-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多