[英]How to listen for specific JSON error code in try/catch statement?
下面的函數異步獲取帖子列表,並將接收到的數據發送到我的應用程序的Redux存儲。
該功能既可以處理初始帖子集的獲取,也可以處理用戶可以通過單擊“加載更多”按鈕觸發的后續帖子。
export const fetchFilteredPosts = (filter, reset) => async(dispatch, getState, api) => {
if (reset) {
dispatch({
type: 'RESET_FILTERED_POSTS'
});
}
dispatch({
type: 'IS_FETCHING_FILTERED_POSTS'
});
try {
const currentPage = getState().filteredPosts.currentPage;
const nextPage = currentPage == 0 ? 1 : (currentPage + 1);
const filteredPosts = await api.get('/wp-json/wp/v2/posts?tag=' + filter + '&page=' + nextPage);
dispatch({
type: 'HAS_FETCHED_FILTERED_POSTS',
payload: {
data: filteredPosts.data,
currentPage: nextPage
}
});
} catch (error) {
dispatch({
type: 'FAILED_FETCHING_FILTERED_POSTS',
payload: error
});
}
}
這是我的Redux商店:
import { filteredPostsPerPage } from '../config';
const initState = {
canFetchMore: false,
currentPage: 0,
data: null,
fetchingError: null,
isFetching: null,
perPage: filteredPostsPerPage
}
export default (state = initState, action) => {
switch (action.type) {
case 'IS_FETCHING_FILTERED_POSTS':
return {
...state,
isFetching: true,
fetchingError: false
}
case 'HAS_FETCHED_FILTERED_POSTS':
const posts = action.payload.data;
return {
...state,
data: state.data === null ? posts : state.data.concat(posts),
isFetching: false,
canFetchMore: posts.length >= state.perPage,
currentPage: action.payload.currentPage
}
case 'FAILED_FETCHING_FILTERED_POSTS':
return {
...state,
isFetching: false,
fetchingError: action.payload
}
case 'RESET_FILTERED_POSTS':
return initState;
default:
return state;
}
}
假設我將10個設置為每頁顯示的帖子數,並且用戶選擇了一個類別,其中恰好有10個帖子。 如果他們要單擊“加載更多”按鈕,則應用程序將引發以下錯誤:
{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
如何在函數的catch
部分中偵聽此確切錯誤,以便向用戶顯示一條消息,例如No more posts in this category
? 我想我需要訪問API請求的響應,但是在這種情況下,我不確定該怎么做。
您不能聽一個特定的錯誤,您必須聽所有。 您可以使用if語句:
try {
/* ... */
} catch (e) {
if (e.data.status === 400) {
/* handle your error */
} else {
}
}
找到了。 這與使用Axios庫有關,我沒有提到我正在使用它,因為我不知道在Axios中需要使用error.response
而不是error
。 因此,如果您使用Axios,則可以按以下方式捕獲錯誤:
try {
/* ... */
} catch (error) {
if (error.response.data.status === 400) {
/* handle your error */
} else {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.