1
0
Fork 0
peertube/server/core/middlewares/error.ts

64 lines
1.6 KiB
TypeScript
Raw Normal View History

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'
import { logger } from '@server/helpers/logger.js'
import { HttpStatusCode } from '@peertube/peertube-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, tags } = options
2021-06-02 12:15:41 -04:00
const extension = new ProblemDocumentExtension({
...data,
docs: res.locals.docUrl,
code: type,
// For <= 3.2 compatibility
error: message
})
const json = new ProblemDocument({
2021-06-02 12:15:41 -04:00
status,
title,
instance,
detail: message,
type: type
? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}`
2021-06-02 12:15:41 -04:00
: undefined
}, extension)
logger.debug('Bad HTTP request.', { json, tags })
2023-09-01 03:27:57 -04: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')
res.json(json)
2021-06-02 12:15:41 -04:00
}
if (next) next()
}
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 {
apiFailMiddleware,
handleStaticError
2021-06-02 12:15:41 -04:00
}