ServeStaticWrapper.mjs 981 B

12345678910111213141516171819202122232425262728293031323334
  1. import express from 'express'
  2. import { plainTextResponse } from './Response.mjs'
  3. /*
  4. This wrapper is implemented specifically to handle "Premature Close" errors.
  5. These errors occur when the client cancels a request while static assets are being loaded.
  6. This issue is beyond our control, it can result in unnecessary log noise.
  7. Therefore, this wrapper is added to handle such errors.
  8. */
  9. function serveStaticWrapper(root, options) {
  10. const serveStatic = express.static(root, options)
  11. return (req, res, next) => {
  12. serveStatic(req, res, error => {
  13. if (!error) {
  14. return next()
  15. }
  16. if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  17. return next(error)
  18. }
  19. req.logger.addFields({ err: error })
  20. req.logger.setLevel('debug')
  21. if (res.headersSent) {
  22. res.end()
  23. } else {
  24. res.status(400)
  25. plainTextResponse(res, 'Premature close')
  26. }
  27. })
  28. }
  29. }
  30. export default serveStaticWrapper