0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-27 21:39:16 -05:00
logto/packages/core/src/middleware/koa-error-handler.ts
simeng-li c8d45a13f0
test(core): add middleware tests [1 of 2] (#244)
* test(core): add middleware tests

add middleware tests

* fix(ut): fix typo

fix typo
2022-02-17 14:21:29 +08:00

25 lines
530 B
TypeScript

import { RequestErrorBody } from '@logto/schemas';
import { Middleware } from 'koa';
import RequestError from '@/errors/RequestError';
export default function koaErrorHandler<StateT, ContextT, BodyT>(): Middleware<
StateT,
ContextT,
BodyT | RequestErrorBody
> {
return async (ctx, next) => {
try {
await next();
} catch (error: unknown) {
if (error instanceof RequestError) {
ctx.status = error.status;
ctx.body = error.body;
return;
}
throw error;
}
};
}