fix: error handle error (#259)

This commit is contained in:
ChengLei Shao 2022-04-03 09:26:45 +08:00 committed by GitHub
parent 02ff296178
commit afa807951a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 0 deletions

View File

@ -1,9 +1,12 @@
import { MockServer, mockServer } from '@nocobase/test'; import { MockServer, mockServer } from '@nocobase/test';
import { PluginErrorHandler } from '../server'; import { PluginErrorHandler } from '../server';
import { Database } from '@nocobase/database';
import supertest from 'supertest';
describe('create with exception', () => { describe('create with exception', () => {
let app: MockServer; let app: MockServer;
beforeEach(async () => { beforeEach(async () => {
app = mockServer(); app = mockServer();
await app.cleanDb();
app.plugin(PluginErrorHandler); app.plugin(PluginErrorHandler);
}); });
@ -117,4 +120,51 @@ describe('create with exception', () => {
], ],
}); });
}); });
it('should handle unique error with raw sql', async () => {
const userCollection = app.collection({
name: 'users',
autoGenId: false,
timestamps: false,
fields: [
{
name: 'name',
type: 'string',
primaryKey: true,
},
],
});
await app.loadAndInstall();
app.resourcer.define({
name: 'test',
actions: {
async test(ctx) {
const db: Database = ctx.db;
const sql = `INSERT INTO ${userCollection.model.tableName} (name)
VALUES (:name)`;
await db.sequelize.query(sql, {
replacements: { name: ctx.action.params.values.name },
type: 'INSERT',
});
},
},
});
const agent = supertest.agent(app.callback());
await agent.post('/test:test').send({
name: 'u1',
});
const response = await agent.post('/test:test').send({
name: 'u1',
});
const body = response.body;
expect(body['errors'][0]['message']).toBeDefined();
});
}); });

View File

@ -20,6 +20,10 @@ export class PluginErrorHandler extends Plugin {
registerSequelizeValidationErrorHandler() { registerSequelizeValidationErrorHandler() {
const findFieldTitle = (instance, path, tFunc) => { const findFieldTitle = (instance, path, tFunc) => {
if (!instance) {
return path;
}
const model = instance.constructor; const model = instance.constructor;
const collection = this.db.modelCollection.get(model); const collection = this.db.modelCollection.get(model);
const field = collection.getField(path); const field = collection.getField(path);