简体   繁体   English

如何在try / catch语句中侦听特定的JSON错误代码?

[英]How to listen for specific JSON error code in try/catch statement?

The function below fetches a list of posts asynchronously and sends the received data to my app's Redux store. 下面的函数异步获取帖子列表,并将接收到的数据发送到我的应用程序的Redux存储。

The function handles both the fetching of the initial set of posts and that of subsequent posts that the user can trigger by clicking on a 'Load more' button. 该功能既可以处理初始帖子集的获取,也可以处理用户可以通过单击“加载更多”按钮触发的后续帖子。

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
    });
  }
}

Here's my Redux store: 这是我的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;
  }
}

Suppose I have set 10 as the number of posts to display per page, and that the user has selected a category in which there are exactly 10 posts. 假设我将10个设置为每页显示的帖子数,并且用户选择了一个类别,其中恰好有10个帖子。 If they're going to click on the Load More button, the app will throw this error: 如果他们要单击“加载更多”按钮,则应用程序将引发以下错误:

{
  "code": "rest_post_invalid_page_number",
  "message": "The page number requested is larger than the number of pages available.",
  "data": {
    "status": 400
  }
}

How can I listen for this exact error in the catch part of my function, so that I can display a message to the user, something like No more posts in this category ? 如何在函数的catch部分中侦听此确切错误,以便向用户显示一条消息,例如No more posts in this category I guess I need to access the API request's response, but I'm not sure how to do that in this case. 我想我需要访问API请求的响应,但是在这种情况下,我不确定该怎么做。

You cant listen to a specific error, you have to listen for all. 您不能听一个特定的错误,您必须听所有。 You could use an if-statement: 您可以使用if语句:

try {

  /* ... */

} catch (e) {

  if (e.data.status === 400) {
    /* handle your error */
  } else {

  }

}

Found it. 找到了。 This has something to do with using the Axios library, which I didn't mention I was using 'cause I didn't know that with Axios you need to work with error.response , not simply error . 这与使用Axios库有关,我没有提到我正在使用它,因为我不知道在Axios中需要使用error.response而不是error So if you use Axios you can catch the error as follows: 因此,如果您使用Axios,则可以按以下方式捕获错误:

try {

  /* ... */

} catch (error) {

  if (error.response.data.status === 400) {
    /* handle your error */
  } else {

  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM