2
1

error.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. export {
  32. apiFailMiddleware
  33. }