diff --git a/api/source/errors.ts b/api/source/errors.ts new file mode 100644 index 000000000..bdf9205dc --- /dev/null +++ b/api/source/errors.ts @@ -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 + } + } +} diff --git a/api/source/index.ts b/api/source/index.ts index e11c37fe4..fe080fac3 100644 --- a/api/source/index.ts +++ b/api/source/index.ts @@ -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))