bai3/note

错误处理

Opened this issue · 0 comments

bai3 commented

错误处理

现在,我们假设远程读取因为某些原因失败了,API函数 Api.fetch返回一个被拒绝的Promise。

我们希望通过在Saga中发起 PRODUCTS_REQUEST_FSILED action 到Store来处理那些错误。

我们可以使用熟悉的try/catch 语法在Saga中捕获错误。

import Api from './path/to/api'
import { call, put } from 'redux-saga/effects'

function* fetchProducts() {
    try {
        const products = yield call(Api.fetch, '/products')
        yield put({ type: 'PRODUCTS_REQUEST_FAILED', products})
    }
    catch(error) {
        yield put({ type: 'PRODUCTS_REQUEST_FAILED', error})
    }
}

为了测试故障案例,我们将使用Generator的throw方法

import { call, put } from 'redux-saga/effects'
import Api from '...'

const iterator = fetchProducts()
//期望一个call指令
assert.deepEqual(
    iterator.next().value,
    call(Api.fetch, '/products'),   
)
//创建一个模拟的error对象
const error = []
//期望一个dispatch指令
assert.deepEqual(
    interator.throw(error).value,
    put({type: 'PRODUCTS_REQUEST_FAILED', error}))
)

当然你并不一定 try/catch 区块处理处理。你可以捕捉Promise的拒绝操作,并将它们映射到一个错误字段对象。

import Api from './path/to/api'
import { call, put } from 'redux-saga/effects'

function fetchProductsApi() {
    return Api.fetch(/products)
                     .then(response => ({ response}))
            		.catch(error => ({error}))
}
function* fetchProducts() {
	const { response, error } = yield call(fetchProductsApi)
    if (response)
        yield put({type: 'PRODUCTS_RECEIVED', products: response0})
    else
        yield put({type: 'PRODUCTS_REQUEST_FSILED', error})
    }