]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/error.ts
Prevent object storage mock conflicts
[github/Chocobozzz/PeerTube.git] / server / middlewares / error.ts
index 34c87a26d8dc7522670c02b357c0d3a095d3c8de..94762e35542bb779b6487d5d91f71d51151a6a2d 100644 (file)
@@ -5,7 +5,7 @@ import { HttpStatusCode } from '@shared/models'
 
 function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) {
   res.fail = options => {
-    const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance } = options
+    const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance, tags } = options
 
     const extension = new ProblemDocumentExtension({
       ...data,
@@ -18,7 +18,10 @@ function apiFailMiddleware (req: express.Request, res: express.Response, next: e
     })
 
     res.status(status)
-    res.setHeader('Content-Type', 'application/problem+json')
+
+    if (!res.headersSent) {
+      res.setHeader('Content-Type', 'application/problem+json')
+    }
 
     const json = new ProblemDocument({
       status,
@@ -32,7 +35,7 @@ function apiFailMiddleware (req: express.Request, res: express.Response, next: e
         : undefined
     }, extension)
 
-    logger.debug('Bad HTTP request.', { json })
+    logger.debug('Bad HTTP request.', { json, tags })
 
     res.json(json)
   }
@@ -40,6 +43,21 @@ function apiFailMiddleware (req: express.Request, res: express.Response, next: e
   if (next) next()
 }
 
+function handleStaticError (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
+  const message = err.message || ''
+
+  if (message.includes('ENOENT')) {
+    return res.fail({
+      status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
+      message: err.message,
+      type: err.name
+    })
+  }
+
+  return next(err)
+}
+
 export {
-  apiFailMiddleware
+  apiFailMiddleware,
+  handleStaticError
 }