Italik
Italik

Reputation: 696

How to properly catch errors in axios get request?

I use openweathermap API to get forecast. App is based on ReactJS and Redux. I have a problem with catch errors. I want to create alert for users when searched city doesn't exists in database. So, I have action like below:

export function fetchWeather (city) {
    const url = `${ROOT_URL}&q=${city}`;
    const request = axios.get(url);

    return (dispatch) => {
        request
         .then(({data}) => {
            dispatch({type: FETCH_WEATHER, payload: data})
         })
         .catch((error) => { 
            dispatch({type: FETCH_WEATHER_ERROR, payload: error})
        });
    };

And my reducer:

import { FETCH_WEATHER, FETCH_WEATHER_ERROR } from '../actions/index';

export default function (state = [], action) {
    switch (action.type) {
    case FETCH_WEATHER:
     console.log(action.payload) //I receive object, so it's ok
        return [...state, action.payload];

    case FETCH_WEATHER_ERROR: 
     console.log(action.payload) // I receive just info in console "Error: Request failed with status code 404"
        return state;
    }
    return state;
}

So, it works properly but I'm curious how to get proper object in error part to simple show alert with message info what happened wrong. Because when I check in inspector tab (Networks) there is nice object in response: {cod: "404", message: "city not found"}, but in console.log(action.payload) I have just info, no object, array... Why are these things different? How to get proper value of error response to show error message?

Upvotes: 0

Views: 997

Answers (1)

HMR
HMR

Reputation: 39320

It looks like the API will always return 200 (success) when the connection works even though there is a 401 not allowed or 404 not found. Check out the following url in your dev tools network tab:

http://samples.openweathermap.org/data/2.5/weather?q=nomatterNoApiKey

So anything going into catch is actual network problem.

request
.then((response) => {
  if(response.cod===200){
    dispatch({type: FETCH_WEATHER, payload: response.data});
  }else{
    dispatch({type: FETCH_WEATHER_ERROR, payload: response.message});
  }
})

You have to make sure that is the correct way to use the API and still have to deal with network errors.

Upvotes: 2

Related Questions