2024-03-26 11:08:15 -05:00
|
|
|
import { HttpStatusCode } from '@peertube/peertube-models'
|
|
|
|
import { logger } from '@server/helpers/logger.js'
|
2021-08-27 07:32:44 -05:00
|
|
|
import express from 'express'
|
2021-06-02 11:15:41 -05:00
|
|
|
import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details'
|
|
|
|
|
|
|
|
function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) {
|
|
|
|
res.fail = options => {
|
2024-03-26 11:08:15 -05:00
|
|
|
const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance, tags, logLevel = 'debug' } = options
|
2021-06-02 11:15:41 -05:00
|
|
|
|
|
|
|
const extension = new ProblemDocumentExtension({
|
|
|
|
...data,
|
|
|
|
|
|
|
|
docs: res.locals.docUrl,
|
|
|
|
code: type,
|
|
|
|
|
|
|
|
// For <= 3.2 compatibility
|
|
|
|
error: message
|
|
|
|
})
|
|
|
|
|
2021-12-08 04:32:45 -06:00
|
|
|
const json = new ProblemDocument({
|
2021-06-02 11:15:41 -05:00
|
|
|
status,
|
|
|
|
title,
|
|
|
|
instance,
|
|
|
|
|
|
|
|
detail: message,
|
|
|
|
|
|
|
|
type: type
|
2023-04-21 07:55:10 -05:00
|
|
|
? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}`
|
2021-06-02 11:15:41 -05:00
|
|
|
: undefined
|
2021-12-08 04:32:45 -06:00
|
|
|
}, extension)
|
|
|
|
|
2024-03-26 11:08:15 -05:00
|
|
|
logger.log(logLevel, 'Bad HTTP request.', { json, tags })
|
2021-12-08 04:32:45 -06:00
|
|
|
|
2023-09-01 02:27:57 -05:00
|
|
|
res.status(status)
|
|
|
|
|
|
|
|
// Cannot display a proper error to the client since headers are already sent
|
|
|
|
if (res.headersSent) return
|
|
|
|
|
|
|
|
res.setHeader('Content-Type', 'application/problem+json')
|
2021-12-08 04:32:45 -06:00
|
|
|
res.json(json)
|
2021-06-02 11:15:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if (next) next()
|
|
|
|
}
|
|
|
|
|
2022-07-27 07:38:07 -05: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 11:15:41 -05:00
|
|
|
export {
|
2022-07-27 07:38:07 -05:00
|
|
|
apiFailMiddleware,
|
|
|
|
handleStaticError
|
2021-06-02 11:15:41 -05:00
|
|
|
}
|