mirror of
https://github.com/yu-i-i/overleaf-cep.git
synced 2026-06-05 07:09:02 +02:00
fbbb39b0c0
Convert Errors with Status Code To HTTP Errors GitOrigin-RevId: 4c7abf4f9164c1a907fbf38c6e440409a616e047
34 lines
908 B
JavaScript
34 lines
908 B
JavaScript
const HttpErrors = require('@overleaf/o-error/http')
|
|
const bodyParser = require('body-parser')
|
|
|
|
const convertToHTTPError = error => {
|
|
if (!error.statusCode || error.statusCode < 400 || error.statusCode >= 600) {
|
|
// cannot be converted to a HttpError
|
|
return error
|
|
}
|
|
|
|
return new HttpErrors.HttpError({
|
|
message: error.message,
|
|
statusCode: error.statusCode
|
|
}).withCause(error)
|
|
}
|
|
|
|
// Wraps a parser and attempt to wrap its error (if any) into a HTTPError so the
|
|
// response code is forwarded to the client
|
|
const wrapBodyParser = method => opts => {
|
|
const middleware = bodyParser[method](opts)
|
|
return (req, res, next) => {
|
|
middleware(req, res, nextArg => {
|
|
if (nextArg instanceof Error) {
|
|
return next(convertToHTTPError(nextArg))
|
|
}
|
|
next(nextArg)
|
|
})
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
urlencoded: wrapBodyParser('urlencoded'),
|
|
json: wrapBodyParser('json')
|
|
}
|