2

When you use the fetch API in JavaScript and the result contains a status code that isn't OK (not 2xx), an error that includes the status code and the method is being logged to the console in most browsers (I've tried Chrome, Edge and Opera). This makes sense, as this type of response usually means some kind of error on your side.

However this error is also present when using a .catch chain on your Promise (this is the most basic code example):

fetch("<some api call that returns a status code of 400>")
    .catch(_ => {});

This gives the same error in the console as not catching it.

If .catch(_ => {}) does not work, is there a way to suppress this error?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
leo848
  • 637
  • 2
  • 7
  • 24
  • 1
    a) `fetch(…).catch(…)` doesn't handle [http errors](https://stackoverflow.com/a/38236296/1048572). You use `.then(response => { if (response.status …) … })` for that b) that still doesn't [suppress the console message](https://stackoverflow.com/q/4500741/1048572). – Bergi Dec 09 '21 at 20:34
  • 1
    "*This makes sense, as this type of response usually means some kind of error on your side.*" - even if the error is not on your side, it's still an error, and still should be logged. Avoid causing errors in the first place if you don't want to see the message :-) – Bergi Dec 09 '21 at 20:39
  • @Bergi that makes sense to me, but if the server returns this status code it's not my fault and I don't want my console to be spammed by these messages. Do you know any method of suppressing it? – leo848 Dec 09 '21 at 20:44
  • 1
    Depends on the kind of error. If 4xx, it is your fault; if 5xx it might not be your fault but you still should stop making requests so that you don't get "spammed". As for suppressing it, I already linked the solution. – Bergi Dec 09 '21 at 20:49
  • @Bergi thanks for that, but the specific API I have to use responds with 400 when you try to automatically log in without ever having logged in before. Since there is no endpoint to check this, I'll have to accept the error. – leo848 Dec 09 '21 at 21:11

0 Answers0