Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: global middleware can't catch error #542

Merged
merged 4 commits into from
Jul 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/faas/src/starter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,13 @@ export class FaaSStarter implements IFaaSStarter {
fnMiddlewere = fnMiddlewere.concat(funOptions.middleware);
if (fnMiddlewere.length) {
const mw: any[] = await this.loadMiddleware(fnMiddlewere);
mw.push(async ctx => {
mw.push(async (ctx, next) => {
// invoke handler
const result = await this.invokeHandler(funOptions, ctx, args);
if (!ctx.body) {
ctx.body = result;
}
return next();
});
return compose(mw)(context).then(() => {
return context.body;
Expand Down Expand Up @@ -231,6 +232,12 @@ export class FaaSStarter implements IFaaSStarter {
this.registerDecorator();
await this.loader.refresh();

// merge app middleware to global
if (this.webApplication?.['middleware']?.length) {
this.globalMiddleware = this.globalMiddleware.concat(
this.webApplication['middleware']
);
}
// set app keys
this.webApplication['keys'] = this.webApplication.getConfig('keys') || '';

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "demo-app"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const middleware = ['testMiddleware'];
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Configuration } from '@midwayjs/decorator';

@Configuration({
importConfigs: ['./config.default'],
})
export class AutoConfiguraion {}
12 changes: 12 additions & 0 deletions packages/faas/test/fixtures/base-app-middleware-err/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { inject, provide, func, FunctionHandler } from '../../../../src';

@provide()
@func('index.handler')
export class HelloService implements FunctionHandler {
@inject()
ctx; // context

handler(event) {
throw new Error('test err');
}
}
14 changes: 14 additions & 0 deletions packages/faas/test/fixtures/base-app-middleware-err/src/mw/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Provide } from '@midwayjs/decorator';

@Provide()
export class TestMiddleware {
resolve() {
return async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.body = 'ahello555'
}
};
}
}
23 changes: 23 additions & 0 deletions packages/faas/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,29 @@ describe('test/index.test.ts', () => {
assert(data.body === 'ahello555');
});

it('test throw error from code and middleware catch it', async () => {
const { start } = require('../../serverless-scf-starter/src');
const runtime = await start();
const starter = new FaaSStarter({
baseDir: join(__dirname, './fixtures/base-app-middleware-err'),
applicationAdapter: runtime,
});
await starter.start();
const data = await runtime.asyncEvent(
starter.handleInvokeWrapper('index.handler')
)(
{
text: 'hello',
httpMethod: 'GET',
headers: {},
requestContext: {},
},
{ text: 'a' }
);

assert(data.body === 'ahello555');
});

it('test inject app and plugin', async () => {
const { start } = require('../../serverless-scf-starter/src');
const runtime = await start();
Expand Down
1 change: 0 additions & 1 deletion packages/serverless-http-parser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"cookies": "^0.8.0",
"encodeurl": "^1.0.2",
"escape-html": "^1.0.3",
"koa-compose": "^4.1.0",
"only": "^0.0.2",
"parseurl": "^1.3.3",
"querystring": "^0.2.0",
Expand Down
8 changes: 1 addition & 7 deletions packages/serverless-http-parser/src/application.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { context } from './context';
import { request } from './request';
import { response } from './response';
import * as compose from 'koa-compose';
import * as only from 'only';
import { EventEmitter } from 'events';
import { format } from 'util';
Expand Down Expand Up @@ -70,17 +69,12 @@ export class Application extends EventEmitter {
*/

callback() {
const fn = compose(this.middleware);
this.on('error', this.onerror);
return (req, res, respond) => {
// if (!this.listenerCount('error')) this.on('error', this.onerror);
const onerror = err => ctx.onerror(err);
const ctx = this.createContext(req, res);
return fn(ctx)
.then(() => {
return respond(ctx);
})
.catch(onerror);
return respond(ctx).catch(onerror);
};
}

Expand Down
10 changes: 5 additions & 5 deletions packages/serverless-http-parser/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,10 @@ describe('test http parser', () => {

it('should test callback', async () => {
const app = new Application();
app.use(async (ctx, next) => {
ctx.aaa = 'test';
await next();
});
// app.use(async (ctx, next) => {
// ctx.aaa = 'test';
// await next();
// });
const req = new HTTPRequest(
require('./resource/scf_apigw.json'),
require('./resource/scf_ctx.json')
Expand All @@ -379,7 +379,7 @@ describe('test http parser', () => {
resolve(ctx);
});
});
assert((ctx as any).aaa === 'test');
// assert((ctx as any).aaa === 'test');
assert.deepStrictEqual(
ctx.originContext,
require('./resource/scf_ctx.json')
Expand Down