2021-08-27 08:32:44 -04:00
|
|
|
import express from 'express'
|
2021-06-02 12:15:41 -04:00
|
|
|
import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
|
2021-12-08 05:32:45 -05:00
|
|
|
import { logger } from '@server/helpers/logger'
|
2021-07-16 04:42:24 -04:00
|
|
|
import { HttpStatusCode } from '@shared/models'
|
2021-06-02 12:15:41 -04:00
|
|
|
|
|
|
|
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)
|
2023-04-14 03:34:53 -04:00
|
|
|
|
|
|
|
if (!res.headersSent) {
|
|
|
|
res.setHeader('Content-Type', 'application/problem+json')
|
|
|
|
}
|
2021-12-08 05:32:45 -05:00
|
|
|
|
|
|
|
const json = new ProblemDocument({
|
2021-06-02 12:15:41 -04:00
|
|
|
status,
|
|
|
|
title,
|
|
|
|
instance,
|
|
|
|
|
|
|
|
detail: message,
|
|
|
|
|
|
|
|
type: type
|
2023-02-22 10:15:14 -05:00
|
|
|
? `https://docs.joinpeertube.org/api/rest-reference.html#section/Errors/${type}`
|
2021-06-02 12:15:41 -04:00
|
|
|
: undefined
|
2021-12-08 05:32:45 -05:00
|
|
|
}, extension)
|
|
|
|
|
|
|
|
logger.debug('Bad HTTP request.', { json })
|
|
|
|
|
|
|
|
res.json(json)
|
2021-06-02 12:15:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (next) next()
|
|
|
|
}
|
|
|
|
|
2022-07-27 08:38:07 -04:00
|
|
|
function handleStaticError (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
|
|
|
|
const message = err.message || ''
|
|
|
|
|
|
|
|
if (message.includes('ENOENT')) {
|
|
|
|
return res.fail({
|
|
|
|
status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
|
|
|
|
message: err.message,
|
|
|
|
type: err.name
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(err)
|
|
|
|
}
|
|
|
|
|
2021-06-02 12:15:41 -04:00
|
|
|
export {
|
2022-07-27 08:38:07 -04:00
|
|
|
apiFailMiddleware,
|
|
|
|
handleStaticError
|
2021-06-02 12:15:41 -04:00
|
|
|
}
|