File tree 2 files changed +52
-2
lines changed
2 files changed +52
-2
lines changed Original file line number Diff line number Diff line change @@ -61,4 +61,50 @@ describe('app.currentContext', () => {
61
61
62
62
await request ( app . callback ( ) ) . get ( '/' ) . expect ( 'ok' )
63
63
} )
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
+ } )
64
110
} )
Original file line number Diff line number Diff line change @@ -81,7 +81,6 @@ module.exports = class Application extends Emitter {
81
81
const { AsyncLocalStorage } = require ( 'async_hooks' )
82
82
assert ( AsyncLocalStorage , 'Requires node 12.17.0 or higher to enable asyncLocalStorage' )
83
83
this . ctxStorage = new AsyncLocalStorage ( )
84
- this . use ( this . createAsyncCtxStorageMiddleware ( ) )
85
84
}
86
85
}
87
86
@@ -160,7 +159,12 @@ module.exports = class Application extends Emitter {
160
159
161
160
const handleRequest = ( req , res ) => {
162
161
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
+ } )
164
168
}
165
169
166
170
return handleRequest
You can’t perform that action at this time.
0 commit comments