Search code examples
node.jsexpressxmlhttprequestaxioshttp-status-code-404

Catch 404 on xhr.js, when Axios GET is called and express server sends .json()


On my client Vue.js application the console gives me an 404 error, when calling my express API, with an invalid API token.

E.g. calling http://localhost:8081/confirmation/invalidToken gives, me

xhr.js?b50d:172 GET http://localhost:8081/confirmation/a 404 (Not Found)

Of course it is possible for someone to use that invalid link, so I want to handle these errors instead of printing the error on the console.

If on my express server side, I send the response, like this:

return res.status(404);

Then the console error disappears. Edit: However this only seems to be the case, because the request is not finished and it's waiting. After a while, the console logs a "net::ERR_CONNECTION_RESET" error.

It's only appearing if I send the response like this:

return res.status(404).send({
  message: 'No valid link!',
  error,
});

or this:

return res.status(404).send({
  message: 'No valid link!',
  error,
});

Catching on client side is not working for this problem.

public async sendConfirmation(token: string): Promise<any> {
  try {
    return axios.get(this.baseURL + '/confirmation/' + token);
  } catch (error) {
  // tslint:disable-next-line:no-console
    console.log(error.response);
  }
}



sendConfirmation(this.token)
 .then((res) => {
   // tslint:disable-next-line:no-console
   console.log(res);
   if (res.status === 404) {
     throw new Error("404");
   }
   this.data = res.data;
   if (res.status === 201) {
     this. messagetype = 1;
   } else if (res.status === 200) {
     this.messagetype = 2;
   }
})
.catch((err) => {
  this.messagetype = 0;
  // tslint:disable-next-line:no-console
  // console.log(err );
});

Anyone knows a way to catch that console error, not having to remove the custom message in the server result?


Solution

  • Well, it's a browser behaviour, that shows the error. Certain response codes, will in some browsers throw those console messages.

    There seems no way to prevent this in a project.