test(plugin-error-handler): middleware (#3909)

* test(plugin-error-handler-middleware): add test case

* chore: test

* chore: handle error throw via ctx.throw

---------

Co-authored-by: Chareice <chareice@live.com>
This commit is contained in:
Junyi 2024-04-03 22:26:35 +08:00 committed by GitHub
parent 187a587e68
commit 1ec5c1c9c2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,64 @@
import { Database } from '@nocobase/database';
import { MockServer, createMockServer } from '@nocobase/test';
import Plugin from '..';
describe('middleware', () => {
let app: MockServer;
beforeEach(async () => {
app = await createMockServer({
acl: false,
plugins: ['error-handler'],
});
});
afterEach(async () => {
await app.destroy();
});
it('should handle not null error', async () => {
const collection = app.db.collection({
name: 'users',
fields: [
{
name: 'name',
type: 'string',
},
],
});
await collection.sync();
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
(app.pm.get(Plugin) as Plugin).errorHandler.register(
(err) => err instanceof CustomError,
(err, ctx) => {
ctx.body = {
errors: [err.message],
};
},
);
app.use(
(ctx, next) => {
ctx.throw(400, new CustomError('custom error'));
},
{ after: 'dataSource' },
);
const response = await app.agent().resource('users').create({
values: {},
});
expect(response.statusCode).toEqual(400);
expect(response.body).toEqual({
errors: ['custom error'],
});
});
});

View File

@ -28,6 +28,10 @@ export class ErrorHandler {
} catch (err) {
ctx.log.error(err.message, { method: 'error-handler', err: err.stack });
if (err.statusCode) {
ctx.status = err.statusCode;
}
for (const handler of self.handlers) {
if (handler.guard(err)) {
return handler.render(err, ctx);