2022-04-26 00:35:40 +08:00
|
|
|
import { Schema } from '@formily/json-schema';
|
2022-03-06 12:07:56 +08:00
|
|
|
import { Plugin } from '@nocobase/server';
|
2022-03-06 16:19:18 +08:00
|
|
|
import lodash from 'lodash';
|
2022-03-06 12:07:56 +08:00
|
|
|
import { BaseError } from 'sequelize';
|
2022-03-06 16:19:18 +08:00
|
|
|
import { ErrorHandler } from './error-handler';
|
2022-03-06 12:07:56 +08:00
|
|
|
import enUS from './locale/en_US';
|
2022-03-06 16:19:18 +08:00
|
|
|
import zhCN from './locale/zh_CN';
|
2022-03-06 12:07:56 +08:00
|
|
|
|
|
|
|
export class PluginErrorHandler extends Plugin {
|
|
|
|
errorHandler: ErrorHandler = new ErrorHandler();
|
|
|
|
i18nNs: string = 'error-handler';
|
|
|
|
|
|
|
|
beforeLoad() {
|
|
|
|
this.registerSequelizeValidationErrorHandler();
|
|
|
|
}
|
|
|
|
|
|
|
|
registerSequelizeValidationErrorHandler() {
|
|
|
|
const findFieldTitle = (instance, path, tFunc) => {
|
2022-04-03 09:26:45 +08:00
|
|
|
if (!instance) {
|
|
|
|
return path;
|
|
|
|
}
|
|
|
|
|
2022-03-06 12:07:56 +08:00
|
|
|
const model = instance.constructor;
|
|
|
|
const collection = this.db.modelCollection.get(model);
|
|
|
|
const field = collection.getField(path);
|
2022-07-25 23:24:18 +08:00
|
|
|
const fieldOptions = Schema.compile(field?.options, { t: tFunc });
|
2022-03-06 12:07:56 +08:00
|
|
|
const title = lodash.get(fieldOptions, 'uiSchema.title', path);
|
|
|
|
return title;
|
|
|
|
};
|
|
|
|
|
|
|
|
this.errorHandler.register(
|
|
|
|
(err) => err?.errors?.length && err instanceof BaseError,
|
|
|
|
(err, ctx) => {
|
|
|
|
ctx.body = {
|
|
|
|
errors: err.errors.map((err) => {
|
|
|
|
return {
|
|
|
|
message: ctx.i18n.t(err.type, {
|
|
|
|
ns: this.i18nNs,
|
|
|
|
field: findFieldTitle(err.instance, err.path, ctx.i18n.t),
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
ctx.status = 400;
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
2022-10-31 22:45:39 +08:00
|
|
|
|
2022-03-06 12:07:56 +08:00
|
|
|
async load() {
|
|
|
|
this.app.i18n.addResources('zh-CN', this.i18nNs, zhCN);
|
|
|
|
this.app.i18n.addResources('en-US', this.i18nNs, enUS);
|
2022-09-29 21:05:31 +08:00
|
|
|
this.app.middleware.nodes.unshift(this.errorHandler.middleware());
|
2022-03-06 12:07:56 +08:00
|
|
|
}
|
|
|
|
}
|