functions.js 884 B

1234567891011121314151617181920212223242526
  1. 'use strict'
  2. /**
  3. * Call the error handler if a middleware function throw an error
  4. *
  5. * @param {Function} fn original middleware function of the route
  6. * @returns {Function} the same middleware function of the route but error handled
  7. */
  8. export const asyncMiddleware = fn => (req, res, next) => {
  9. Promise.resolve(fn(req, res, next)).catch(err => {
  10. // Check whether the error is a boom error
  11. if (!err.isBoom) {
  12. // The error was not recognized, send a 500 HTTP error
  13. return next(boom.internal(err))
  14. }
  15. // It is a boom error, pass it to the error handler
  16. next(err)
  17. })
  18. }
  19. // Middleware to handle middleware errors
  20. export const errorHandler = (err, req, res, next) => {
  21. const { output: { payload } } = err
  22. console.error(`Error ${payload.statusCode} - ${payload.error}\n${payload.message}\n`)
  23. return res.status(payload.statusCode).json(payload)
  24. }