在 redux saga 中获取响应而不是错误
Get response instead of error in redux saga
我想知道如何处理 redux saga 中的错误响应,我仍在学习并且正在这样做:
export function* loginUserSaga(action) {
try {
const user = action.payload
const responseData = yield call(loginUser, user);
yield put(succeededLoginRequest(responseData));
} catch (e) {
yield put(failedLoginRequest(e.message));
}
}
是否有其他方法可以处理该问题以便我可以获得响应而不是错误?正如我在文档中看到的那样,您通常使用 try catch 向 API
发出请求
Try..catch 通常是可行的方法,但您可以修改 loginUser 对 return 具有 response/error 字段的对象的响应,然后使用条件而不是 try..catch。
这是来自文档 (https://redux-saga.js.org/docs/basics/ErrorHandling.html) 的示例:
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: response })
else
yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
}
我想知道如何处理 redux saga 中的错误响应,我仍在学习并且正在这样做:
export function* loginUserSaga(action) {
try {
const user = action.payload
const responseData = yield call(loginUser, user);
yield put(succeededLoginRequest(responseData));
} catch (e) {
yield put(failedLoginRequest(e.message));
}
}
是否有其他方法可以处理该问题以便我可以获得响应而不是错误?正如我在文档中看到的那样,您通常使用 try catch 向 API
发出请求Try..catch 通常是可行的方法,但您可以修改 loginUser 对 return 具有 response/error 字段的对象的响应,然后使用条件而不是 try..catch。
这是来自文档 (https://redux-saga.js.org/docs/basics/ErrorHandling.html) 的示例:
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: response })
else
yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
}