koa异常处理

 

全局处理异常:

https://blog.csdn.net/weixin_44867717/article/details/131949819

 

更简洁的写法

复制代码
router.post('/:tick', async(ctx, next) => { // 特定tick
  const params = ctx.request.params;
  const ids = params.tick

  try {
    let sql = `
      SELECT src20_tick_v4.*, src20_mint_progress_v4.*
      FROM ${SRC20_TICK_TABLE} s, ${SRC20_MINT_PROGRESS_TABLE}
      WHERE s.id=src20_mint_progress_v4.id and src20_tick_v4.id='${ids}'
    `
    let res = await knex.raw(sql)
    const resMap = []
    for (let each of res.rows) {
      resMap.push({
        tick: each.tick,
        stamp_url: each.stamp_url,
        max: each.max ? each.max : "",
        lim: each.lim ? each.lim : "",
        amt: new Decimal(each.amt),
        dec: each.dec ? each.dec : 18,
        creator: each.creator,
        tx_hash: each.tx_hash,
        block_index: each.block_index,
        block_time: each.block_time,
      })
    }
    ctx.body = success(resMap.length ? resMap[0] : {})
  } catch (e) {
    // console.log('---------', e.status, e.statusCode, e.message);
    ctx.body = fail(e.message);
  }

  
  
})
复制代码

不需要asCallback了。

 

 

在函数内部处理:

复制代码
router.post('/:tick', async(ctx, next) => { // 特定tick
  const params = ctx.request.params;
  const ids = params.tick

  let sql = `
    SELECT src20_tick_v4.*, src20_mint_progress_v4.*
    FROM ${SRC20_TICK_TABLE} s, ${SRC20_MINT_PROGRESS_TABLE}
    WHERE s.id=src20_mint_progress_v4.id and src20_tick_v4.id='${ids}'
  `
  let res = []
  try {
    res = await knex.raw(sql).asCallback(function(err) {
      if (err) {
        // console.log(false, err, err.message);
        // ctx.body = fail(err.message);
        // throw err;
        // console.log(false, err);
      } else {
        // console.log(true);
        const resMap = []
        for (let each of res.rows) {
          resMap.push({
            tick: each.tick,
            stamp_url: each.stamp_url,
            max: each.max ? each.max : "",
            lim: each.lim ? each.lim : "",
            amt: new Decimal(each.amt),
            dec: each.dec ? each.dec : 18,
            creator: each.creator,
            tx_hash: each.tx_hash,
            block_index: each.block_index,
            block_time: each.block_time,
          })
        }
        ctx.body = success(resMap.length ? resMap[0] : {})
      }
    })
  } catch (e) {
    // console.log('---------', e.status, e.statusCode, e.message);
    ctx.body = fail(e.message);
  }

  
  
})
复制代码

sql有问题,被try catch捕获。而不asCallback中的err,但asCallback中的err里包含相同信息。

 

posted @   走走停停走走  Views(27)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2020-12-25 go 如何单测
点击右上角即可分享
微信分享提示