Unverified Commit 669cad97 authored by Amith Mihiranga's avatar Amith Mihiranga Committed by GitHub

Fix: with-mongodb-mongoose example improper fetch error handling (#15856)

Correct the error handling for fetch API to check if the status is ok or not

FIxes #15808 
parent f9cb5ac6
...@@ -33,6 +33,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => { ...@@ -33,6 +33,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
}, },
body: JSON.stringify(form), body: JSON.stringify(form),
}) })
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
const { data } = await res.json() const { data } = await res.json()
mutate(`/api/pets/${id}`, data, false) // Update the local data without a revalidation mutate(`/api/pets/${id}`, data, false) // Update the local data without a revalidation
...@@ -45,7 +51,7 @@ const Form = ({ formId, petForm, forNewPet = true }) => { ...@@ -45,7 +51,7 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
/* The POST method adds a new entry in the mongodb database. */ /* The POST method adds a new entry in the mongodb database. */
const postData = async (form) => { const postData = async (form) => {
try { try {
await fetch('/api/pets', { const res = await fetch('/api/pets', {
method: 'POST', method: 'POST',
headers: { headers: {
Accept: contentType, Accept: contentType,
...@@ -53,6 +59,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => { ...@@ -53,6 +59,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
}, },
body: JSON.stringify(form), body: JSON.stringify(form),
}) })
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
router.push('/') router.push('/')
} catch (error) { } catch (error) {
setMessage('Failed to add pet') setMessage('Failed to add pet')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment