ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

error.ts 1.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { HttpStatusCode } from '@peertube/peertube-models'
  2. import { logger } from '@server/helpers/logger.js'
  3. import express from 'express'
  4. import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
  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, tags, logLevel = 'debug' } = 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. const json = new ProblemDocument({
  16. status,
  17. title,
  18. instance,
  19. detail: message,
  20. type: type
  21. ? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}`
  22. : undefined
  23. }, extension)
  24. logger.log(logLevel, 'Bad HTTP request.', { json, tags })
  25. res.status(status)
  26. // Cannot display a proper error to the client since headers are already sent
  27. if (res.headersSent) return
  28. res.setHeader('Content-Type', 'application/problem+json')
  29. res.json(json)
  30. }
  31. if (next) next()
  32. }
  33. function handleStaticError (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
  34. const message = err.message || ''
  35. if (message.includes('ENOENT')) {
  36. return res.fail({
  37. status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
  38. message: err.message,
  39. type: err.name
  40. })
  41. }
  42. return next(err)
  43. }
  44. export {
  45. apiFailMiddleware,
  46. handleStaticError
  47. }