Giter Site home page Giter Site logo

Comments (5)

nodejh avatar nodejh commented on July 16, 2024 1

https://github.com/ChenShenhai/koa2-note/blob/master/note/mysql/async.md

这个文件还没改过来呢

from koa2-note.

chenshenhai avatar chenshenhai commented on July 16, 2024

谢谢指正错误,已经修改好了,O(∩_∩)O!

from koa2-note.

chenshenhai avatar chenshenhai commented on July 16, 2024

谢谢提醒,改好了,O(∩_∩)O

from koa2-note.

jackgreentemp avatar jackgreentemp commented on July 16, 2024

msyql发生异常时,只在db-utils.js中调用reject(),但是没有在上层调用的地方捕获异常,会触发unhandledpromiserejectionwarning。
教程中的demo好像对这部分没有进行说明(mysql部分也没有),是否可以补充一下?

from koa2-note.

jackgreentemp avatar jackgreentemp commented on July 16, 2024

db-utils.js中增加catch,实现全局处理

let query = function( sql, values ) {

  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        resolve( err )
      } else {
        connection.query(sql, values, ( err, rows) => {

          if ( err ) {
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  }).catch((e) => {
    console.log("mysql error")
    console.log(e)
  })

}

或者在models里进行局部处理

/**
     * 更新username
     * @param  {object} model 用户数据模型
     * @return {object}       mysql执行结果
     */
    async setUserName (model) {
        let _sql = "UPDATE ?? SET ? WHERE id = ?"
        let result = await dbUtils.query(_sql, [ 'user', {names: model.name}, model.userId ] ).catch((e) => {
            console.log("setUserName mysql error")
            console.log(e)
        })
        return result
    },

但是有一个问题,再捕获到异常后,怎么将异常提示给controller并返回,有什么好的处理方式?
一个笨办法就是:models返回promise给services,services中返回promise给controllers,在controller中catch异常,使用ctx.throw()把error抛给app.js中进行全局处理

app.js中错误处理,可以参考阮一峰老师的例子
https://github.com/ruanyf/koa-demos/blob/master/demos/16.js
引用阮老师的教程:为了方便处理错误,最好使用try...catch将其捕获。但是,为每个中间件都写try...catch太麻烦,我们可以让最外层的中间件,负责所有中间件的错误处理。

const handler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.response.status = err.statusCode || err.status || 500;
    ctx.response.body = {
      message: err.message
    };
  }
};

const main = ctx => {
  ctx.throw(500);
};

app.use(handler);
app.use(main);

from koa2-note.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.