I'm using Axios to fetch some data:
export const getProducts = async () => {
try {
const { data } = await axios.get(`/api/products`)
return data
} catch (err) {
console.log(err)
return err
}
}
Everything is fine, but I need to catch http errors inside try block. For example, when connection with the server is lost, Axios returns an AxiosError object:
- AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
- code: "ERR_BAD_REQUEST"
- config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
- message: "Request failed with status code 404"
- name: "AxiosError"
- request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
- response: {data: '\n\n\n<meta char…re>Cannot GET /api/prducts\n\n\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}
- stack: "AxiosError: Request failed with status code 404\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)"
- [[Prototype]]: Error
The problem is: I want to render a div saying "There was an error fetching the data" if there is an error. If not, render a table with products as usual.
I call my function like this:
const productsArr = await getProducts()
How can I recognize if productsArr is a valid product array, or an AxiosError?