Fix l'erreur lorsqu'un json est mal formaté
parent
880cb6c04e
commit
d1ade51691
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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))
|
||||
|
|
Loading…
Reference in New Issue