2021-08-23 21:29:58 +08:00
|
|
|
import { LogtoErrorCode } from '@logto/phrases';
|
2021-08-30 11:30:54 +08:00
|
|
|
import { RequestErrorBody } from '@logto/schemas';
|
2021-07-06 23:29:36 +08:00
|
|
|
import decamelize from 'decamelize';
|
2021-07-06 23:12:35 +08:00
|
|
|
import { Middleware } from 'koa';
|
2021-07-06 23:29:36 +08:00
|
|
|
import { errors } from 'oidc-provider';
|
2021-07-06 23:12:35 +08:00
|
|
|
|
2021-08-30 11:30:54 +08:00
|
|
|
import RequestError from '@/errors/RequestError';
|
|
|
|
|
2021-07-06 23:12:35 +08:00
|
|
|
export default function koaErrorHandler<StateT, ContextT>(): Middleware<
|
|
|
|
StateT,
|
|
|
|
ContextT,
|
|
|
|
RequestErrorBody
|
|
|
|
> {
|
|
|
|
return async (ctx, next) => {
|
|
|
|
try {
|
|
|
|
await next();
|
|
|
|
} catch (error: unknown) {
|
|
|
|
if (error instanceof RequestError) {
|
|
|
|
ctx.status = error.status;
|
|
|
|
ctx.body = error.body;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-07-06 23:29:36 +08:00
|
|
|
if (error instanceof errors.OIDCProviderError) {
|
|
|
|
ctx.status = error.status;
|
|
|
|
ctx.body = {
|
|
|
|
message: error.error_description ?? error.message,
|
2021-08-23 21:29:58 +08:00
|
|
|
// Assert error type of OIDCProviderError, code key should all covered in @logto/phrases
|
|
|
|
code: `oidc.${decamelize(error.name)}` as LogtoErrorCode,
|
2021-07-06 23:29:36 +08:00
|
|
|
data: error.error_detail,
|
|
|
|
};
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-07-06 23:12:35 +08:00
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|