错误处理的时候遇到的一个问题
一般错误处理
koa.use(async (ctx,next)=>{
try{
await next();
console.log('next executed')
}
catch(e){
console.error(e);
}
})
koa.use(async (ctx,next)=>{
console.log('error happen')
return Promise.reject('error')
})
如果这时 这样添加中间件 错误不会抛出
koa.use(async (ctx,next)=>{
try{
await next();
console.log('next executed')
}
catch(e){
console.error(e);
}
})
koa.use(async (ctx,next)=>{
console.log('middle')
next();
})
koa.use(async (ctx,next)=>{
console.log('error happen')
return Promise.reject('error')
})
这样会收到 unhandled Promise 的错误
加一个return 即可
koa.use(async (ctx,next)=>{
console.log('middle')
return next();
})
参照源码 koa-compose
return function (context, next) {
// last called middleware #
let index = -1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, function next () {
return dispatch(i + 1)
}))
} catch (err) {
return Promise.reject(err)
}
}
}
是直接resolve 中间件的 执行结果,如果不加return 就等于
koa.use(async (ctx,next)=>{
console.log('middle')
next();
return undefined;
})
所以抛出的 错误就无法捕捉