0

I am running the following code trying to delete a "scream" that does not exist:

// Delete a scream
exports.deleteScream = (req, res) => {
  const document = db.doc(`/screams/${req.params.screamId}`);
  document.get()
    .then(doc => {
      if(!doc.exists){
        console.log("1")
        return res.status(404).json({ error: 'Scream not found'});
        console.log("2")
      }
      if(doc.data.userHandle !== req.user.handle){
        return res.status(403).json({ error: 'Unathorized'});
      } else {
        return document.delete();
      }
    })
    .then(() => {
      console.log("3")
      return res.json({ message: 'Scream deleted successfully'});
      console.log("4")
    })
    .catch(err => {
      console.error(err);
      console.log("5")
      return res.status(500).json({ error: err.code });
    });
};

The console log shows the follwing:

>  1
>  3
>  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
>      at ServerResponse.setHeader (_http_outgoing.js:516:11)
>      at ServerResponse.header (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:771:10)
>      at ServerResponse.send (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:170:12)
>      at ServerResponse.json (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:267:15)
>      at /Users/sm/projects/socialape/functions/handlers/screams.js:227:18
>      at processTicksAndRejections (internal/process/task_queues.js:93:5) {
>    code: 'ERR_HTTP_HEADERS_SENT'
>  }
>  5
>  (node:4032) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
>      at ServerResponse.setHeader (_http_outgoing.js:516:11)
>      at ServerResponse.header (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:771:10)
>      at ServerResponse.send (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:170:12)
>      at ServerResponse.json (/Users/sm/projects/socialape/functions/node_modules/express/lib/response.js:267:15)
>      at /Users/sm/projects/socialape/functions/handlers/screams.js:233:30
>      at processTicksAndRejections (internal/process/task_queues.js:93:5)
>  (node:4032) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
>  (node:4032) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I would expect the function to stop executing at the 404 response, but it appears like both then blocks are executed in addition the the catch block. Why is this the case?

Mandark
  • 5
  • 2
  • Does this answer your question? [ERR\_HTTP\_HEADERS\_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client) – Anurag Srivastava Mar 28 '20 at 18:08

1 Answers1

2

If you return inside a then function, you are returning only that anonymous function. It is not return from parent. You should throw an exception and return in catch.

const document = db.doc(`/screams/${req.params.screamId}`);
document
  .get()
  .then(doc => {
    if (!doc.exists) throw new Error(404);
    return doc;
  })
  .then(doc => {
    if (doc.data.userHandle !== req.user.handle) {
      throw new Error(403);
    } else {
      document.delete();
    }
    return doc;
  })
  .then(() => {
    res.json({ message: "Scream deleted successfully" });
  })
  .catch(error => {
    switch (error.message) {
      case 403:
        res.status(error.message).send({ error: "Unathorized" });
        break;
      case 404:
        res.status(error.message).send({ error: "Scream not found" });
        break;
      default:
        res.status(error.message).send({ error: error.message });
        break;
    }
  });
Mandark
  • 5
  • 2
xdeepakv
  • 7,835
  • 2
  • 22
  • 32