2021-08-30 11:30:54 +08:00
|
|
|
import { RequestErrorBody } from '@logto/schemas';
|
2021-07-06 23:12:35 +08:00
|
|
|
import { Middleware } from 'koa';
|
|
|
|
|
2021-08-30 11:30:54 +08:00
|
|
|
import RequestError from '@/errors/RequestError';
|
|
|
|
|
2022-02-17 14:21:29 +08:00
|
|
|
export default function koaErrorHandler<StateT, ContextT, BodyT>(): Middleware<
|
2021-07-06 23:12:35 +08:00
|
|
|
StateT,
|
|
|
|
ContextT,
|
2022-02-17 14:21:29 +08:00
|
|
|
BodyT | RequestErrorBody
|
2021-07-06 23:12:35 +08:00
|
|
|
> {
|
|
|
|
return async (ctx, next) => {
|
|
|
|
try {
|
|
|
|
await next();
|
|
|
|
} catch (error: unknown) {
|
|
|
|
if (error instanceof RequestError) {
|
|
|
|
ctx.status = error.status;
|
|
|
|
ctx.body = error.body;
|
2022-01-27 19:26:34 +08:00
|
|
|
|
2021-07-06 23:12:35 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|