In my redux I got this axios get call As you can see I already throw the err here
export const getShippingMethodById = (token, id) => {
return (dispatch) => {
const config = {
headers: {
Authorization: `bearer ${token}`,
'Content-Type': 'application/json',
},
};
return axios
.get(`${baseUri}/api/checkout/GetShippingById?addressId=${id}`, config)
.then((res) => {
dispatch({
type: FETCH_SHIPPING_METHOD_BY_ID,
payload: res.data.shippingInfos,
});
})
.catch((err) => {
console.log(err);
throw err;
alert('Cannot connect to server');
});
};
};
In the functional component, inside the useEffect hooks I am calling this function
useEffect(() => {
let splitText = cartList?.OrderDTO?.DeliveryCountry;
let deliveryAddressId = splitText?.split(',');
if (
cartList.OrderDTO?.DeliveryCountry !== '' &&
deliveryAddressId !== undefined
) {
dispatch(
getShippingMethodById(token.access_token, Number(deliveryAddressId[1])),
).then((res) => {
console.log(res);
});
} else {
dispatch(
getShippingMethodById(
token.access_token,
cartList.OrderDTO?.CustomerAddressId,
),
).then((res) => {
console.log(res);
});
}
}, [cartList]);
But when ever this component is loaded I got this error
Since I already handle the promise rejection Why am I getting this error?
Because you are using throw err;
in catch
block. You need to remove it. You can read more about throw
in here: https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Statements/throw
Throwing an error from a catch
won't be caught by the same catch block being executed. This means you are returning a Promise rejection to your UI code and the error should then be caught there. Add a catch
to the Promise chain.
useEffect(() => {
let splitText = cartList?.OrderDTO?.DeliveryCountry;
let deliveryAddressId = splitText?.split(',');
if (
cartList.OrderDTO?.DeliveryCountry !== '' &&
deliveryAddressId !== undefined
) {
dispatch(
getShippingMethodById(token.access_token, Number(deliveryAddressId[1])),
).then((res) => {
console.log(res);
}).catch(error => {
// handle rejected Promise or any other error from this chain
});
} else {
dispatch(
getShippingMethodById(
token.access_token,
cartList.OrderDTO?.CustomerAddressId,
),
).then((res) => {
console.log(res);
}).catch(error => {
// handle rejected Promise or any other error from this chain
});
}
}, [cartList]);
Or simply remove rethrowing the error:
return axios
.get(`${baseUri}/api/checkout/GetShippingById?addressId=${id}`, config)
.then((res) => {
dispatch({
type: FETCH_SHIPPING_METHOD_BY_ID,
payload: res.data.shippingInfos,
});
})
.catch((err) => {
console.log(err);
// no error rethrow
alert('Cannot connect to server');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.