Asynchronous/await methods for error handling using Axios in React
P粉186904731
2023-08-26 10:41:39
<p>I'm using Axios to get some data: </p>
<pre class="brush:php;toolbar:false;">export const getProducts = async () => {
try {
const { data } = await axios.get(`/api/products`)
return data
} catch (err) {
console.log(err)
return err
}
}</pre>
<p>Everything is fine, but I need to catch http errors inside a try block. For example, when the connection to the server is lost, Axios returns an AxiosError object: </p>
<blockquote>
<ol>
<li>AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request:
XMLHttpRequest,...}</li>
<li>Code: "ERR_BAD_REQUEST"</li>
<li>Configuration: {transition: {…}, adapter: array(2), transformRequest: array(1), transformResponse: array(1), timeout: 0,
…}</li>
<li>Message: "Request failed with status code 404"</li>
<li>Name: "AxiosError"</li>
<li>Request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
…}</li>
<li>Response: {data: 'nnn<metacharacters...re>cannot be retrieved
/api/productsnnn', status: 404, statusText: 'No
Found ', Headers: AxiosHeaders, Configuration: {...},...}</li>
<li>Stack: "AxiosError: Request failed with status code 404n while resolving
(webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)n
in XMLHttpRequest.onloadend
(webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)"</li>
<li>[[Prototype]]: Error</li>
</ol>
</blockquote>
<p>The problem is: if there is an error, I want to render a div that says "An error occurred while getting data". If there are no errors, render a product table in the usual way. </p>
<p>I call my function like this: </p>
<pre class="brush:php;toolbar:false;">const productsArr = await getProducts()</pre>
<p>How do I tell if productsArr is a valid array of products or an AxiosError? </p>
You can see how to handle errors in the official documentation: https://axios-http.com/docs/handling_errors
If no response is received, you can view the error (copied from axios documentation)
You can wrap your component with error handling boundaries. You can create a component that will wrap other components where the error occurs and use the
componentDidCatch
lifecycle methods, which is the same as usingcatch{}
in a try-catch. https://reactjs.org/docs/react-component.html#componentdidcatch. Or use a popular npm packagehttps://www.npmjs.com/package/react-error-boundary