aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/error.ts
blob: e3eb1c8f54b8bc94d5943e692d9f9cfb503f980d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import * as express from 'express'
import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
import { HttpStatusCode } from '@shared/core-utils'

function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) {
  res.fail = options => {
    const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance } = options

    const extension = new ProblemDocumentExtension({
      ...data,

      docs: res.locals.docUrl,
      code: type,

      // For <= 3.2 compatibility
      error: message
    })

    res.status(status)
    res.setHeader('Content-Type', 'application/problem+json')
    res.json(new ProblemDocument({
      status,
      title,
      instance,

      detail: message,

      type: type
        ? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}`
        : undefined
    }, extension))
  }

  if (next) next()
}

export {
  apiFailMiddleware
}