最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

什么是起泡和使用异步 AWAIT捕获异常正确的模式?

IT培训 admin 4浏览 0评论

什么是起泡和使用异步/ AWAIT捕获异常正确的模式?

我挣扎着我的头缠着什么正确的模式是嵌套等待/异步程序中处理错误,但保持代码干净和简单。 (尽管阅人无数的文章和博客)

我有一组功能,这些功能(基本上)类似以下内容:

async validate(params) {
    const recCount = await this._getCount(db, params);

    if( recCount > 0 )
        return "Record already exists";
}

_getCount是创建SQL包装

async _getCount(conn, regdata) {
    const sql = "SELECT count(*) AS 'count' FROM myTable WHERE product = ? and category = ?";
    let rows = await this._execSQL(conn, sql, [ regdata.product, regdata.category ]);
    return rows[0].count;
}

和如下实际执行查询:

async _execSQL(conn, sql, data) {
    const [ rows ] = await conn.query(sql, data);
    return rows;
}

如果查询失败的方法conn.query(来自mysql2 /诺库)将拒绝该承诺。

所以,我的问题是什么是处理例外的正确模式?

在同步的世界里,我会没事的_execSQL也不_getCount,只是赶上验证除外;很自然地让异常泡沫了。

然而,在异步世界我该怎么办没有得到的“未处理无极”异常相同呢?

我是不是坚持了其捕获错误,在通过各级每一个异步例行一路?

或者是有没有使用类似process.on('unhandledRejection',...)感觉就像我避开了问题的一个更好的办法?

编辑:添加例子和堆栈跟踪

好了,其实我已经将此代码添加到我的应用程序,并把try / catch语句在validate功能。逐字的代码是:

async validate(db, params) {
    let recCount;

    try {
        recCount = await this._getCount(db, params);
    } catch (err) {
        console.log('Caught error', err);
    }

    if (recCount > 0) return 'Record already exists';
}

async _getCount(conn, regdata) {
    const sql = "SELECT count(*) AS 'count' FROM myTable WHERE product = ? and category = ?";
    let rows = await this._execSQL(conn, sql, [ regdata.product, regdata.category ]);
    return rows[0].count;
}

async _execSQL(conn, sql, data) {
    const [ rows ] = await conn.query(sql, data);
    return rows;
}

我有一个unhandledRejection事件处理程序,它用堆栈跟踪沿着内部异常一起报告了该事件。这是它转储出:

Stack Trace:

AppError: Unhandled promise rejection.   Plugin may not be properly handling error.
    at process.on (D:\Development\website\service\server.js:73:5)
    at emitTwo (events.js:126:13)
    at process.emit (events.js:214:7)
    at emitPendingUnhandledRejections (internal/process/promises.js:108:22)
    at process._tickCallback (internal/process/next_tick.js:189:7)

Inner Error:

{   "message": "connect ECONNREFUSED 127.0.0.1:3306",   "code": "ECONNREFUSED",   "errno": "ECONNREFUSED" }

Error: connect ECONNREFUSED 127.0.0.1:3306
    at PromisePool.query (D:\Development\website\webhooks\node_modules\mysql2\promise.js:323:22)
    at Registration._execSQL (D:\Development\website\webhooks\plugins\registration.js:108:31)
    at Registration._logRequest (D:\Development\website\webhooks\plugins\registration.js:179:14)
    at Registration.register (D:\Development\website\webhooks\plugins\registration.js:52:8)
    at Router.exec (D:\Development\website\service\router.js:119:20)
    at IncomingMessage.request.on (D:\Development\website\service\server.js:292:47)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
回答如下:

您可以随时让拒绝冒泡并选择最佳的水平赶上他们:

async function f1() { return await f2(); }
async function f2() { return await f3(); }
async function f3() {
  return Promise.reject('no way!');
  // or
  throw 'no way!';
}

async function f_await() {
  try {
    console.log('never succeeds here', await f1());
  } catch (err) {
    console.log('I check for errors at the level I prefer!');
    throw 'I can even intercept and rethrow!';
  }
  return 'or i can keep going like eveything is fine';
}
function f_then() {
  f1().then(console.log.bind(null, 'never succeeds here'))
  .catch(function (err) {
    console.log('I check for errors at the level I prefer!');
    throw 'I can even intercept and rethrow!';
  }).then(function () {
    return 'or i can keep going like eveything is fine';
  });
}

如果触发未处理的拒绝警告,那是因为......你没在链中的任何一点处理一些排斥,而你总是需要:即使在同步码,如果有异常上升,从来没有抓到,电脑会告诉你这是多么不开心。

如果你想处理一个SQL查询的最佳方式被拒绝在你的代码是在validate,然后去了:围绕这个awaittry / catch块和catch“处理”的错误,你的思维方式是最好的...不知道我看到这里的问题!

什么是起泡和使用异步/ AWAIT捕获异常正确的模式?

我挣扎着我的头缠着什么正确的模式是嵌套等待/异步程序中处理错误,但保持代码干净和简单。 (尽管阅人无数的文章和博客)

我有一组功能,这些功能(基本上)类似以下内容:

async validate(params) {
    const recCount = await this._getCount(db, params);

    if( recCount > 0 )
        return "Record already exists";
}

_getCount是创建SQL包装

async _getCount(conn, regdata) {
    const sql = "SELECT count(*) AS 'count' FROM myTable WHERE product = ? and category = ?";
    let rows = await this._execSQL(conn, sql, [ regdata.product, regdata.category ]);
    return rows[0].count;
}

和如下实际执行查询:

async _execSQL(conn, sql, data) {
    const [ rows ] = await conn.query(sql, data);
    return rows;
}

如果查询失败的方法conn.query(来自mysql2 /诺库)将拒绝该承诺。

所以,我的问题是什么是处理例外的正确模式?

在同步的世界里,我会没事的_execSQL也不_getCount,只是赶上验证除外;很自然地让异常泡沫了。

然而,在异步世界我该怎么办没有得到的“未处理无极”异常相同呢?

我是不是坚持了其捕获错误,在通过各级每一个异步例行一路?

或者是有没有使用类似process.on('unhandledRejection',...)感觉就像我避开了问题的一个更好的办法?

编辑:添加例子和堆栈跟踪

好了,其实我已经将此代码添加到我的应用程序,并把try / catch语句在validate功能。逐字的代码是:

async validate(db, params) {
    let recCount;

    try {
        recCount = await this._getCount(db, params);
    } catch (err) {
        console.log('Caught error', err);
    }

    if (recCount > 0) return 'Record already exists';
}

async _getCount(conn, regdata) {
    const sql = "SELECT count(*) AS 'count' FROM myTable WHERE product = ? and category = ?";
    let rows = await this._execSQL(conn, sql, [ regdata.product, regdata.category ]);
    return rows[0].count;
}

async _execSQL(conn, sql, data) {
    const [ rows ] = await conn.query(sql, data);
    return rows;
}

我有一个unhandledRejection事件处理程序,它用堆栈跟踪沿着内部异常一起报告了该事件。这是它转储出:

Stack Trace:

AppError: Unhandled promise rejection.   Plugin may not be properly handling error.
    at process.on (D:\Development\website\service\server.js:73:5)
    at emitTwo (events.js:126:13)
    at process.emit (events.js:214:7)
    at emitPendingUnhandledRejections (internal/process/promises.js:108:22)
    at process._tickCallback (internal/process/next_tick.js:189:7)

Inner Error:

{   "message": "connect ECONNREFUSED 127.0.0.1:3306",   "code": "ECONNREFUSED",   "errno": "ECONNREFUSED" }

Error: connect ECONNREFUSED 127.0.0.1:3306
    at PromisePool.query (D:\Development\website\webhooks\node_modules\mysql2\promise.js:323:22)
    at Registration._execSQL (D:\Development\website\webhooks\plugins\registration.js:108:31)
    at Registration._logRequest (D:\Development\website\webhooks\plugins\registration.js:179:14)
    at Registration.register (D:\Development\website\webhooks\plugins\registration.js:52:8)
    at Router.exec (D:\Development\website\service\router.js:119:20)
    at IncomingMessage.request.on (D:\Development\website\service\server.js:292:47)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
回答如下:

您可以随时让拒绝冒泡并选择最佳的水平赶上他们:

async function f1() { return await f2(); }
async function f2() { return await f3(); }
async function f3() {
  return Promise.reject('no way!');
  // or
  throw 'no way!';
}

async function f_await() {
  try {
    console.log('never succeeds here', await f1());
  } catch (err) {
    console.log('I check for errors at the level I prefer!');
    throw 'I can even intercept and rethrow!';
  }
  return 'or i can keep going like eveything is fine';
}
function f_then() {
  f1().then(console.log.bind(null, 'never succeeds here'))
  .catch(function (err) {
    console.log('I check for errors at the level I prefer!');
    throw 'I can even intercept and rethrow!';
  }).then(function () {
    return 'or i can keep going like eveything is fine';
  });
}

如果触发未处理的拒绝警告,那是因为......你没在链中的任何一点处理一些排斥,而你总是需要:即使在同步码,如果有异常上升,从来没有抓到,电脑会告诉你这是多么不开心。

如果你想处理一个SQL查询的最佳方式被拒绝在你的代码是在validate,然后去了:围绕这个awaittry / catch块和catch“处理”的错误,你的思维方式是最好的...不知道我看到这里的问题!

发布评论

评论列表 (0)

  1. 暂无评论