koa 中间件 的 错误抛出

本文探讨了在Koa框架中使用中间件进行错误处理的方法。重点介绍了如何正确使用Promise.reject和return next()来确保错误能够被上层中间件捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误处理的时候遇到的一个问题

一般错误处理

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;
    })

所以抛出的 错误就无法捕捉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值