I have the following code:
let response = null;
try {
response = await fetch(url, { method,
headers: {
Authorization: `Bearer ${accessToken}`,
}
});
console.log("Status", response?.status);
} catch (e) {
console.log("Error", e);
console.log("Response", response);
}
My request fails with status code 403, but I cannot get this 403
from nowhere. The code above doesn’t get to the line console.log("Status", response?.status);
, instead it goes into catch
section, where response
is undefined
and e
is error with message "TypeError: Failed to fetch"
and stacktrace, but without any further details about the response (actually, I looked for response status code).
Does anybody have idea how do I get that status code (403
in my example) when fetch fails into catch section?
2
Answers
Try using
response.ok
https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
Using your example:
By using ‘response.ok’ you’re checking for error codes 200-299
In such cases, it might be beneficial to handle the response status within the catch block by examining the error object directly, as the response object might not be accessible. Here’s an alternative approach: