fix: custom error handler

This commit is contained in:
chenos 2022-03-02 22:50:07 +08:00
parent 5785f30075
commit 18b4feb104

View File

@ -5,12 +5,11 @@ import { Command } from 'commander';
import i18next from 'i18next'; import i18next from 'i18next';
import { DefaultContext, DefaultState } from 'koa'; import { DefaultContext, DefaultState } from 'koa';
import bodyParser from 'koa-bodyparser'; import bodyParser from 'koa-bodyparser';
import { BaseError } from 'sequelize';
import Application, { ApplicationOptions } from './application'; import Application, { ApplicationOptions } from './application';
import { dataWrapping } from './middlewares/data-wrapping'; import { dataWrapping } from './middlewares/data-wrapping';
import { table2resource } from './middlewares/table2resource'; import { table2resource } from './middlewares/table2resource';
import ValidationError from 'sequelize';
export function createDatabase(options: ApplicationOptions) { export function createDatabase(options: ApplicationOptions) {
if (options.database instanceof Database) { if (options.database instanceof Database) {
return options.database; return options.database;
@ -97,12 +96,11 @@ export function createCli(app: Application, options: ApplicationOptions): Comman
function registerErrorHandler(app: Application) { function registerErrorHandler(app: Application) {
app.errorHandler.register( app.errorHandler.register(
(err) => err.name == 'SequelizeValidationError', (err) => err?.errors?.length && err instanceof BaseError,
(err, ctx) => { (err, ctx) => {
ctx.body = { ctx.body = {
errors: err.errors.map((err) => ({ message: err.message })), errors: err.errors.map((err) => ({ message: err.message })),
}; };
ctx.status = 400; ctx.status = 400;
}, },
); );