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: can not get currentContext in error handler #1758

Merged
merged 1 commit into from
Apr 12, 2023
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
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