error.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import express from 'express'
  2. import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
  3. import { logger } from '@server/helpers/logger'
  4. import { HttpStatusCode } from '@shared/models'
  5. function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) {
  6. res.fail = options => {
  7. const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance } = options
  8. const extension = new ProblemDocumentExtension({
  9. ...data,
  10. docs: res.locals.docUrl,
  11. code: type,
  12. // For <= 3.2 compatibility
  13. error: message
  14. })
  15. res.status(status)
  16. res.setHeader('Content-Type', 'application/problem+json')
  17. const json = new ProblemDocument({
  18. status,
  19. title,
  20. instance,
  21. detail: message,
  22. type: type
  23. ? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}`
  24. : undefined
  25. }, extension)
  26. logger.debug('Bad HTTP request.', { json })
  27. res.json(json)
  28. }
  29. if (next) next()
  30. }
  31. function handleStaticError (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
  32. const message = err.message || ''
  33. if (message.includes('ENOENT')) {
  34. return res.fail({
  35. status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
  36. message: err.message,
  37. type: err.name
  38. })
  39. }
  40. return next(err)
  41. }
  42. export {
  43. apiFailMiddleware,
  44. handleStaticError
  45. }