fix: internal-server-error in case of middleware plugin crashing in the 'after' phase (like happened for max-downloads-ip on response 304)

Massimo Melina committed Mar 12, 2023 at 14:47 UTC 43c35d889017d0f7b6b5ad8eb1a486d073ae06e4
1 file changed +12 -7
src/plugins.ts
+12 -7
@@ -76,7 +76,7 @@ export function getPluginConfigFields(id: string) {
76
77 export function pluginsMiddleware(): Koa.Middleware {
78 return async (ctx, next) => {
79 - const after = []
79 + const after: Dict<CallMeAfter> = {}
80 // run middleware plugins
81 for (const [id,pl] of Object.entries(plugins))
82 try {
@@ -84,11 +84,10 @@ export function pluginsMiddleware(): Koa.Middleware {
84 if (res === true)
85 ctx.pluginStopped = true
86 if (typeof res === 'function')
87 - after.push(res)
87 + after[id] = res
88 }
89 catch(e){
90 - console.log('error middleware plugin', id, String(e))
91 - console.debug(e)
90 + printError(id, e)
91 }
92 // expose public plugins' files
93 const { path } = ctx
@@ -102,8 +101,14 @@ export function pluginsMiddleware(): Koa.Middleware {
101 }
102 await next()
103 }
105 - for (const f of after)
106 - await f()
104 + for (const [id,f] of Object.entries(after))
105 + try { await f() }
106 + catch (e) { printError(id, e) }
107 + }
108 +
109 + function printError(id: string, e: any) {
110 + console.log('error middleware plugin', id, String(e))
111 + console.debug(e)
112 }
113 }
114
@@ -170,7 +175,7 @@ export class Plugin {
175
176 type PluginMiddleware = (ctx:Koa.Context) => void | Stop | CallMeAfter
177 type Stop = true
173 -type CallMeAfter = ()=>void
178 +type CallMeAfter = ()=>any
179
180 export interface AvailablePlugin {
181 id: string