2022-02-14 11:50:47 +08:00
|
|
|
/**
|
|
|
|
* Slonik Error Types:
|
|
|
|
*
|
|
|
|
* BackendTerminatedError,
|
|
|
|
* CheckIntegrityConstraintViolationError,
|
|
|
|
* ConnectionError,
|
|
|
|
* DataIntegrityError,
|
|
|
|
* ForeignKeyIntegrityConstraintViolationError,
|
|
|
|
* IntegrityConstraintViolationError,
|
|
|
|
* InvalidConfigurationError,
|
|
|
|
* InvalidInputError,
|
|
|
|
* NotFoundError,
|
|
|
|
* NotNullIntegrityConstraintViolationError,
|
|
|
|
* StatementCancelledError,
|
|
|
|
* StatementTimeoutError,
|
|
|
|
* UnexpectedStateError,
|
|
|
|
* UniqueIntegrityConstraintViolationError,
|
|
|
|
* TupleMovedToAnotherPartitionError
|
|
|
|
*
|
|
|
|
* (reference)[https://github.com/gajus/slonik#error-handling]
|
|
|
|
*/
|
|
|
|
|
2022-03-02 15:44:57 +08:00
|
|
|
import { SchemaLike } from '@logto/schemas';
|
2022-02-14 11:50:47 +08:00
|
|
|
import { Middleware } from 'koa';
|
|
|
|
import { SlonikError, NotFoundError } from 'slonik';
|
|
|
|
|
|
|
|
import RequestError from '@/errors/RequestError';
|
2022-03-02 15:44:57 +08:00
|
|
|
import { DeletionError, InsertionError, UpdateError } from '@/errors/SlonikError';
|
2022-02-14 11:50:47 +08:00
|
|
|
|
|
|
|
export default function koaSlonikErrorHandler<StateT, ContextT>(): Middleware<StateT, ContextT> {
|
|
|
|
return async (ctx, next) => {
|
|
|
|
try {
|
|
|
|
await next();
|
|
|
|
} catch (error: unknown) {
|
|
|
|
if (!(error instanceof SlonikError)) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (error.constructor) {
|
2022-03-02 15:44:57 +08:00
|
|
|
case InsertionError:
|
|
|
|
throw new RequestError({
|
|
|
|
code: 'entity.create_failed',
|
|
|
|
name: (error as InsertionError<SchemaLike>).schema.tableSingular,
|
|
|
|
});
|
|
|
|
case UpdateError:
|
|
|
|
throw new RequestError({
|
|
|
|
code: 'entity.not_exists',
|
|
|
|
name: (error as InsertionError<SchemaLike>).schema.tableSingular,
|
|
|
|
});
|
2022-02-14 11:50:47 +08:00
|
|
|
case DeletionError:
|
|
|
|
case NotFoundError:
|
|
|
|
throw new RequestError({
|
|
|
|
code: 'entity.not_found',
|
|
|
|
status: 404,
|
|
|
|
});
|
|
|
|
default:
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|