How to detect a 401 with axios and stop the console error : <p>I am trying to use axios to call an API and return data.</p>

<p>I have the following code which works fine</p>

<pre><code>axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response =&gt; {
    console.log(response.data)
  });
</code></pre>

<p>This works fine, the API returns a 200 and data so in the console I get the data returned.</p>

<p>However this does not work</p>

<pre><code>axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response =&gt; {
    console.log(response.data)
  });
</code></pre>

<p>On the above call i get a 401 returned from the API, I want to be able to detect that and do something (where i am currently doing a console.log). However in the console I get the following errors:</p>

<pre><code>GET http://api/courses 401 (Unauthorized)
(anonymous) @ spread.js:25
e.exports @ spread.js:25
e.exports @ spread.js:25
Promise.then (async)
r.request @ spread.js:25
r.(anonymous function) @ spread.js:25
(anonymous) @ index.js:20
(anonymous) @ (index):49


(index):58 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at axios.get.catch.then.response ((index):58)
at &lt;anonymous&gt;
</code></pre>

<p>Is there a way to capture a 401? It seems like common practice by API's that require auth, but I cannot seem to work it out.
Thanks</p>
