Skip to content

Commit e98b8d1

Browse files
authored
fix: can not get currentContext in error handler (koajs#1758)
1 parent bec13ec commit e98b8d1

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
@@ -81,7 +81,6 @@ module.exports = class Application extends Emitter {
8181
const { AsyncLocalStorage } = require('async_hooks')
8282
assert(AsyncLocalStorage, 'Requires node 12.17.0 or higher to enable asyncLocalStorage')
8383
this.ctxStorage = new AsyncLocalStorage()
84-
this.use(this.createAsyncCtxStorageMiddleware())
8584
}
8685
}
8786

@@ -160,7 +159,12 @@ module.exports = class Application extends Emitter {
160159

161160
const handleRequest = (req, res) => {
162161
const ctx = this.createContext(req, res)
163-
return this.handleRequest(ctx, fn)
162+
if (!this.ctxStorage) {
163+
return this.handleRequest(ctx, fn)
164+
}
165+
return this.ctxStorage.run(ctx, async () => {
166+
return await this.handleRequest(ctx, fn)
167+
})
164168
}
165169

166170
return handleRequest

0 commit comments

Comments
 (0)