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

emit more events #1395

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
correct events in case of error
  • Loading branch information
tinovyatkin committed Oct 18, 2019
commit 31911c4ef995637be6c316a3101fa810bf7dd73b
12 changes: 9 additions & 3 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,18 @@ module.exports = class Application extends Emitter {
handleRequest(ctx, fnMiddleware) {
const res = ctx.res;
res.statusCode = 404;

const responding = Symbol('responding');
this.once(responding, () => this.emit('respond', ctx));

const onerror = err => {
if (null != err) ctx.onerror(err);
this.emit('responded', ctx);
if (null != err) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the old code will execute onerror no matter the err is null or not. So I think this is a breaking change.

Copy link
Contributor Author

@tinovyatkin tinovyatkin Oct 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fengmk2 onerror in current implementation just returns immediately if err is null, so, nothing breaks here actually.

ctx.onerror(err);
this.emit(responding);
} else this.emit('responded', ctx);
};
const handleResponse = () => {
this.emit('respond', ctx);
this.emit(responding);
respond(ctx);
};
this.emit('request', ctx);
Expand Down
5 changes: 2 additions & 3 deletions test/application/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('app emits events', () => {
it('should emit error event on middleware throw', async() => {
const app = new Koa();
const emitted = [];
app.on('error', err => emitted.push(err));
['request', 'respond', 'responded', 'error'].forEach(event => app.on(event, () => emitted.push(event)));

app.use((ctx, next) => {
throw new TypeError('Hello Koa!');
Expand All @@ -66,8 +66,7 @@ describe('app emits events', () => {
.get('/')
.expect(500);

assert.deepStrictEqual(emitted.length, 1);
assert.ok(emitted[0] instanceof TypeError);
assert.deepStrictEqual(emitted, ['request', 'error', 'respond', 'responded']);
assert.strictEqual(onceEvents, 1);
});
});