Skip to content

Commit

Permalink
fix: can not get currentContext in error handler (#1758)
Browse files Browse the repository at this point in the history
  • Loading branch information
gxkl committed Apr 12, 2023
1 parent bec13ec commit e98b8d1
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
46 changes: 46 additions & 0 deletions __tests__/application/currentContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,50 @@ describe('app.currentContext', () => {

await request(app.callback()).get('/').expect('ok')
})

it('should get currentContext return context in error handler when asyncLocalStorage enable', async () => {
const app = new Koa({ asyncLocalStorage: true })

app.use(async () => {
throw new Error('error message')
})

const handleError = new Promise((resolve, reject) => {
app.on('error', (err, ctx) => {
try {
assert.strictEqual(err.message, 'error message')
assert.strictEqual(app.currentContext, ctx)
resolve()
} catch (e) {
reject(e)
}
})
})

await request(app.callback()).get('/').expect('Internal Server Error')
await handleError
})

it('should get currentContext return undefined in error handler when asyncLocalStorage disable', async () => {
const app = new Koa()

app.use(async () => {
throw new Error('error message')
})

const handleError = new Promise((resolve, reject) => {
app.on('error', (err, ctx) => {
try {
assert.strictEqual(err.message, 'error message')
assert.strictEqual(app.currentContext, undefined)
resolve()
} catch (e) {
reject(e)
}
})
})

await request(app.callback()).get('/').expect('Internal Server Error')
await handleError
})
})
8 changes: 6 additions & 2 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ module.exports = class Application extends Emitter {
const { AsyncLocalStorage } = require('async_hooks')
assert(AsyncLocalStorage, 'Requires node 12.17.0 or higher to enable asyncLocalStorage')
this.ctxStorage = new AsyncLocalStorage()
this.use(this.createAsyncCtxStorageMiddleware())
}
}

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

const handleRequest = (req, res) => {
const ctx = this.createContext(req, res)
return this.handleRequest(ctx, fn)
if (!this.ctxStorage) {
return this.handleRequest(ctx, fn)
}
return this.ctxStorage.run(ctx, async () => {
return await this.handleRequest(ctx, fn)
})
}

return handleRequest
Expand Down

0 comments on commit e98b8d1

Please sign in to comment.