aboutsummaryrefslogblamecommitdiffhomepage
path: root/server/middlewares/error.ts
blob: 34c87a26d8dc7522670c02b357c0d3a095d3c8de (plain) (tree)
1
2
3
4
                             
                                                                                
                                               
                                               















                                                                                                      
                                      







                                                                                        



                                               






                   
import express from 'express'
import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
import { logger } from '@server/helpers/logger'
import { HttpStatusCode } from '@shared/models'

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')

    const json = new ProblemDocument({
      status,
      title,
      instance,

      detail: message,

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

    logger.debug('Bad HTTP request.', { json })

    res.json(json)
  }

  if (next) next()
}

export {
  apiFailMiddleware
}