From 669cad973134d42b9aeb75ef952914c8e82839b5 Mon Sep 17 00:00:00 2001 From: Amith Mihiranga <39789194+lwpamihiranga@users.noreply.github.com> Date: Wed, 5 Aug 2020 13:07:29 +0530 Subject: [PATCH] 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 --- examples/with-mongodb-mongoose/components/Form.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/examples/with-mongodb-mongoose/components/Form.js b/examples/with-mongodb-mongoose/components/Form.js index 0336c5fb5c8c2..968df84a86ba6 100644 --- a/examples/with-mongodb-mongoose/components/Form.js +++ b/examples/with-mongodb-mongoose/components/Form.js @@ -33,6 +33,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => { }, 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() mutate(`/api/pets/${id}`, data, false) // Update the local data without a revalidation @@ -45,7 +51,7 @@ const Form = ({ formId, petForm, forNewPet = true }) => { /* The POST method adds a new entry in the mongodb database. */ const postData = async (form) => { try { - await fetch('/api/pets', { + const res = await fetch('/api/pets', { method: 'POST', headers: { Accept: contentType, @@ -53,6 +59,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => { }, 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('/') } catch (error) { setMessage('Failed to add pet')