Fix l'erreur lorsqu'un json est mal formaté

pull/2162/head
Jérémy Rialland 2022-06-16 23:58:04 +02:00 committed by Jérémy Rialland
parent 880cb6c04e
commit d1ade51691
2 changed files with 29 additions and 0 deletions

26
api/source/errors.ts Normal file
View File

@ -0,0 +1,26 @@
import { Middleware } from 'koa'
type JsonError = { status: number; body: string; message: string }
const isJsonError = (err: unknown): err is JsonError =>
!!err &&
typeof err === 'object' &&
'message' in err &&
'status' in err &&
'body' in err &&
(err as { status: unknown }).status === 400 &&
typeof (err as { body: unknown }).body === 'string' &&
typeof (err as { message: unknown }).message === 'string'
export const catchErrors = (): Middleware => async (ctx, next) => {
try {
await next()
} catch (error) {
if (isJsonError(error)) {
ctx.status = error.status
ctx.body = error.message
} else {
throw error
}
}
}

View File

@ -4,6 +4,7 @@ import { koaMiddleware as publicodesAPI } from '@publicodes/api'
import Koa from 'koa'
import rules from 'modele-social'
import Engine from 'publicodes'
import { catchErrors } from './errors.js'
import openapi from './openapi.json' assert { type: 'json' }
import { docRoutes } from './route/doc.js'
import { openapiRoutes } from './route/openapi.js'
@ -29,6 +30,8 @@ if (process.env.NODE_ENV === 'production') {
})
}
app.use(catchErrors())
app.use(cors())
const apiRoutes = publicodesAPI(new Engine(rules))