@@ -49,6 +49,8 @@ export const createPropagateErrorToClientErrorHandleMiddleware = (
49
49
) : ErrorHandle => {
50
50
const userFunctionErrorHandle =
51
51
getFirstUserFunctionErrorHandleMiddleware ( userFunction ) ;
52
+ const nextMiddlewareAfterErrorHandleMiddleware =
53
+ getNextMiddlewareAfterErrorMiddleware ( userFunction ) ;
52
54
53
55
return function (
54
56
err : Error ,
@@ -58,6 +60,16 @@ export const createPropagateErrorToClientErrorHandleMiddleware = (
58
60
) {
59
61
// Propagate error to user function error handle.
60
62
if ( userFunctionErrorHandle ) {
63
+ // If the user has a further middleware stack after the error handle middleware,
64
+ // continue the chain, otherwise, propagate to the default error handle.
65
+ if ( nextMiddlewareAfterErrorHandleMiddleware ) {
66
+ return userFunctionErrorHandle (
67
+ err ,
68
+ req ,
69
+ res ,
70
+ nextMiddlewareAfterErrorHandleMiddleware
71
+ ) ;
72
+ }
61
73
return userFunctionErrorHandle ( err , req , res , next ) ;
62
74
}
63
75
@@ -73,17 +85,50 @@ export const createPropagateErrorToClientErrorHandleMiddleware = (
73
85
const getFirstUserFunctionErrorHandleMiddleware = (
74
86
userFunction : HandlerFunction
75
87
) : ErrorHandle | null => {
88
+ const errorHandleMiddlewareIndex =
89
+ getFirstUserFunctionErrorHandleMiddlewareIndex ( userFunction ) ;
90
+ if ( ! errorHandleMiddlewareIndex ) {
91
+ return null ;
92
+ }
93
+
94
+ return ( userFunction as Express ) . _router . stack [ errorHandleMiddlewareIndex ]
95
+ . handle as unknown as ErrorHandle ;
96
+ } ;
97
+
98
+ const getNextMiddlewareAfterErrorMiddleware = (
99
+ userFunction : HandlerFunction
100
+ ) : NextFunction | null => {
101
+ const errorHandleMiddlewareIndex =
102
+ getFirstUserFunctionErrorHandleMiddlewareIndex ( userFunction ) ;
103
+ if ( ! errorHandleMiddlewareIndex ) {
104
+ return null ;
105
+ }
106
+
107
+ const nextMiddlewareAfterErrorHandleIndex = errorHandleMiddlewareIndex + 1 ;
108
+ const middlewares : ILayer [ ] = ( userFunction as Express ) . _router . stack ;
109
+ if ( middlewares . length - 1 < nextMiddlewareAfterErrorHandleIndex ) {
110
+ return null ;
111
+ }
112
+
113
+ return middlewares [ nextMiddlewareAfterErrorHandleIndex ]
114
+ . handle as NextFunction ;
115
+ } ;
116
+
117
+ const getFirstUserFunctionErrorHandleMiddlewareIndex = (
118
+ userFunction : HandlerFunction
119
+ ) : number | null => {
76
120
if ( ! isExpressApp ( userFunction ) ) {
77
121
return null ;
78
122
}
79
123
80
124
const middlewares : ILayer [ ] = ( userFunction as Express ) . _router . stack ;
81
- for ( const middleware of middlewares ) {
125
+ for ( let index = 0 ; index < middlewares . length ; index ++ ) {
126
+ const middleware = middlewares [ index ] ;
82
127
if (
83
128
middleware . handle &&
84
129
middleware . handle . length === EXPRESS_ERROR_HANDLE_PARAM_LENGTH
85
130
) {
86
- return middleware . handle as unknown as ErrorHandle ;
131
+ return index ;
87
132
}
88
133
}
89
134
0 commit comments