Parcourir la source

Fix api error handler

rigwild il y a 5 ans
Parent
commit
4c500568a3
3 fichiers modifiés avec 21 ajouts et 12 suppressions
  1. 12 7
      server/functions.js
  2. 6 0
      server/index.js
  3. 3 5
      server/routes/listScenes.js

+ 12 - 7
server/functions.js

@@ -13,18 +13,23 @@ import { logger, imagesPath, fileNameConvention, sceneFileNameBlackList } from '
  */
 export const asyncMiddleware = fn => (req, res, next) => {
   Promise.resolve(fn(req, res, next)).catch(err => {
-    // Check whether the error is a boom error
-    if (!err.isBoom) {
-      // The error was not recognized, send a 500 HTTP error
-      return next(boom.internal(err))
-    }
-    // It is a boom error, pass it to the error handler
     next(err)
   })
 }
 
 // Middleware to handle middleware errors
 export const errorHandler = (err, req, res, next) => {
+  // Check whether the error is a boom error
+  if (!err.isBoom) {
+    // Check if error is invalid JSON body
+    if (err instanceof SyntaxError && err.status === 400 && err.hasOwnProperty('body'))
+      err = boom.badRequest(err)
+    else {
+      // The error was not recognized, send a 500 HTTP error
+      err = boom.internal(err)
+    }
+  }
+
   const { output: { payload } } = err
 
   // Pass the error to the logging handler
@@ -51,7 +56,7 @@ export const errorHandler = (err, req, res, next) => {
  * @throws missing parameters
  */
 export const checkRequiredParameters = (requiredParameters, parameters) => {
-  if (!requiredParameters.every(aRequiredParameter => Object.keys(parameters).includes(aRequiredParameter)))
+  if (!requiredParameters.every(aRequiredParameter => parameters.hasOwnProperty(aRequiredParameter)))
     throw boom.badRequest(`Missing parameter(s). Required parameters : ${requiredParameters.join(', ')}.`)
 }
 

+ 6 - 0
server/index.js

@@ -6,6 +6,8 @@ import compression from 'compression'
 import serveStatic from 'serve-static'
 import helmet from 'helmet'
 import cors from 'cors'
+import bodyParser from 'body-parser'
+
 import routes from './routes'
 import { errorHandler, formatLog } from './functions'
 import { apiPrefix, imageServedUrl, serverPort, serveClient, imagesPath, logger } from '../config'
@@ -14,6 +16,7 @@ import connectDb from './database'
 const morgan = require('morgan')
 
 const app = express()
+app.enable('trust proxy')
 
 // Activating logging
 app.use(morgan('combined', {
@@ -29,6 +32,9 @@ app.use(helmet())
 // Turn "Cross-origin resource sharing" on to allow remote clients to connect to the API
 app.use(cors())
 
+// Parse JSON body
+app.use(bodyParser.json())
+
 // Serve images. "serve-static" is used because it caches images ("express.static" doesn't)
 app.use(imageServedUrl, serveStatic(imagesPath))
 

+ 3 - 5
server/routes/listScenes.js

@@ -45,11 +45,9 @@ const router = express.Router()
  * @returns {string[]} the list of files
  * @throws the directory does not exist or is not accessible
  */
-export const getSceneList = () => {
-  return fs.readdir(imagesPath).catch(() => {
-    throw boom.internal(`Can't access the "${path.basename(imagesPath)}" directory. Check it exists and you have read permission on it.`)
-  })
-}
+export const getSceneList = () => fs.readdir(imagesPath).catch(() => {
+  throw boom.internal(`Can't access the "${path.basename(imagesPath)}" directory. Check it exists and you have read permission on it.`)
+})
 
 // Route which returns a list of all available scenes in the `imagesPath` directory
 router.get('/', asyncMiddleware(async (req, res) => res.json({ data: await getSceneList() })))