Skip to content

Commit 6b60fa6

Browse files
authored
fix: can not get currentContext in error handler (#1757)
1 parent 34519d1 commit 6b60fa6

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

__tests__/application/currentContext.js

+46
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,50 @@ describe('app.currentContext', () => {
6161

6262
await request(app.callback()).get('/').expect('ok');
6363
});
64+
65+
it('should get currentContext return context in error handler when asyncLocalStorage enable', async() => {
66+
const app = new Koa({ asyncLocalStorage: true });
67+
68+
app.use(async() => {
69+
throw new Error('error message');
70+
});
71+
72+
const handleError = new Promise((resolve, reject) => {
73+
app.on('error', (err, ctx) => {
74+
try {
75+
assert.strictEqual(err.message, 'error message');
76+
assert.strictEqual(app.currentContext, ctx);
77+
resolve();
78+
} catch (e) {
79+
reject(e);
80+
}
81+
});
82+
});
83+
84+
await request(app.callback()).get('/').expect('Internal Server Error');
85+
await handleError;
86+
});
87+
88+
it('should get currentContext return undefined in error handler when asyncLocalStorage disable', async() => {
89+
const app = new Koa();
90+
91+
app.use(async() => {
92+
throw new Error('error message');
93+
});
94+
95+
const handleError = new Promise((resolve, reject) => {
96+
app.on('error', (err, ctx) => {
97+
try {
98+
assert.strictEqual(err.message, 'error message');
99+
assert.strictEqual(app.currentContext, undefined);
100+
resolve();
101+
} catch (e) {
102+
reject(e);
103+
}
104+
});
105+
});
106+
107+
await request(app.callback()).get('/').expect('Internal Server Error');
108+
await handleError;
109+
});
64110
});

lib/application.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ module.exports = class Application extends Emitter {
6969
const { AsyncLocalStorage } = require('async_hooks');
7070
assert(AsyncLocalStorage, 'Requires node 12.17.0 or higher to enable asyncLocalStorage');
7171
this.ctxStorage = new AsyncLocalStorage();
72-
this.use(this.createAsyncCtxStorageMiddleware());
7372
}
7473
}
7574

@@ -154,7 +153,12 @@ module.exports = class Application extends Emitter {
154153

155154
const handleRequest = (req, res) => {
156155
const ctx = this.createContext(req, res);
157-
return this.handleRequest(ctx, fn);
156+
if (!this.ctxStorage) {
157+
return this.handleRequest(ctx, fn);
158+
}
159+
return this.ctxStorage.run(ctx, async() => {
160+
return await this.handleRequest(ctx, fn);
161+
});
158162
};
159163

160164
return handleRequest;

0 commit comments

Comments
 (0)