search

Home  >  Q&A  >  body text

Asynchronous/await methods for error handling using Axios in React

<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>
P粉186904731P粉186904731494 days ago557

reply all(1)I'll reply

  • P粉066224086

    P粉0662240862023-08-27 09:21:06

    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)

    else if (error.request) {
          // 发送请求但未收到响应
          // `error.request` 在浏览器中是XMLHttpRequest的实例,在node.js中是http.ClientRequest的实例
          console.log(error.request);

    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 using catch{} 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

    reply
    0
  • Cancelreply