grazdev
grazdev

Reputation: 1272

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.

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:

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. 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? I guess I need to access the API request's response, but I'm not sure how to do that in this case.

Upvotes: 0

Views: 75

Answers (2)

grazdev
grazdev

Reputation: 1272

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. So if you use Axios you can catch the error as follows:

try {

  /* ... */

} catch (error) {

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

  }

}

Upvotes: 0

Code Spirit
Code Spirit

Reputation: 5029

You cant listen to a specific error, you have to listen for all. You could use an if-statement:

try {

  /* ... */

} catch (e) {

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

  }

}

Upvotes: 1

Related Questions