Next.js fetch() not throwing error on failed request?

A little confused with this one. I'm making requests with the fetch api but when the response returns an error (400) it doesn't acknowledge that and it's not caught. is there something I'm doing wrong?
fetch("http://127.0.0.1:5000/public/auth/sign-in", {
method: "POST",
body: formData,
cache: "no-store",
})
.then((res) => res.json())
.then((data) => console.log("hi"))
.catch((err) => console.log(err));
fetch("http://127.0.0.1:5000/public/auth/sign-in", {
method: "POST",
body: formData,
cache: "no-store",
})
.then((res) => res.json())
.then((data) => console.log("hi"))
.catch((err) => console.log(err));
No description
1 Reply
ATOMowy_grzyb
ATOMowy_grzyb14mo ago
fetch does not throw on HTTP errors, it only throws on network errors you need to check res.ok which will be false if the HTTP code of the response isn't in the 2xx range so
fetch("foo", { options })
.then((res) => { if !(res.ok) throw new Error('o shit'); return res.json(); })
.then((data) => doSomething(data)
.catch((e) => console.error(e));
fetch("foo", { options })
.then((res) => { if !(res.ok) throw new Error('o shit'); return res.json(); })
.then((data) => doSomething(data)
.catch((e) => console.error(e));
that is because a response of HTTP 400 You Done Goofed is not a failed request, it's a successful request that returned a HTTP error status
Want results from more Discord servers?
Add your server