1

If a user makes a request to my API with a payload that is too large, I would like to intercept the error thrown by the server and handle it myself in order to send a more detailed JSON response to the client.

I am using the Express JSON Parser with a custom limit:

router.use(express.json({ limit: "10kb" }));

If a user makes a request over that limit, they currently get an error on the client side and I can't seem to figure out how to try/catch on my server in order to replace the error with a JSON response.

EDIT: I sort of figured this out by setting the limit to Infinity, but I feel like there's probably a better solution. I think that this won't break anything since I am still handling requests that are too large myself.

Arcanist
  • 46
  • 6

1 Answers1

1

You can write your own middleware and attach it before your bodyparser. In that middleware, you can check the Content-Length header of your request, and return an error if it's too large.

If you want to do this only for JSON bodies (for instance if you also allow uploading images), you can also add a condition to check for the contenttype

router.use((req, res, next) => {
   //contents other than json don't have a size limit
   //so just continue with the next handler in the chain
   if (!/^application\/json/.test(req.headers['content-type']))
     return next();

   //get the size from content-length header
   let size = +req.headers['content-length'] || 0;
   //if it's too big, return an error status
   if (size > 10000)
     return res.status(413).send("too big ...");

   //continue with the next handler in the chain
   next(); 
});

//as you already checked the size of the body before
//you don't need the limit here anymore
router.use(express.json());

You can also define different size limits for various content-types.

derpirscher
  • 14,418
  • 3
  • 18
  • 35