[英]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.