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 @@ -69,7 +69,6 @@ module.exports = class Application extends Emitter {
69
69
const { AsyncLocalStorage } = require ( 'async_hooks' ) ;
70
70
assert ( AsyncLocalStorage , 'Requires node 12.17.0 or higher to enable asyncLocalStorage' ) ;
71
71
this . ctxStorage = new AsyncLocalStorage ( ) ;
72
- this . use ( this . createAsyncCtxStorageMiddleware ( ) ) ;
73
72
}
74
73
}
75
74
@@ -154,7 +153,12 @@ module.exports = class Application extends Emitter {
154
153
155
154
const handleRequest = ( req , res ) => {
156
155
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
+ } ) ;
158
162
} ;
159
163
160
164
return handleRequest ;
You can’t perform that action at this time.
0 commit comments