使用 async/await 冒泡和捕获异常的正确模式是什么?
What is the proper pattern for bubbling and catching exceptions using async/await?
我正在努力思考在嵌套 await/async 例程中处理错误的正确模式是什么,同时保持代码简洁明了。 (尽管阅读了无数文章和博客)
我有一组(从根本上)类似于以下的函数:
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/promise库)将拒绝承诺.
所以,我的问题变成了处理异常的正确模式是什么?
在同步世界中,我对 _execSQL 和 _getCount 都无能为力,只能捕获 中的异常验证;自然而然地让异常冒泡。
但是,在异步世界中,我如何在不获得 'Unhandled Promise' 异常的情况下做同样的事情?
我是否一直坚持必须在所有关卡中捕获每个异步例程中的错误?
或者有没有更好的方法而不使用像 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
中,那么就去做吧:用 [=] 包围这个 await
13=]/catch
块和 "handle" 错误 catch
你认为最好的方式......不确定我在这里看到问题!
我正在努力思考在嵌套 await/async 例程中处理错误的正确模式是什么,同时保持代码简洁明了。 (尽管阅读了无数文章和博客)
我有一组(从根本上)类似于以下的函数:
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/promise库)将拒绝承诺.
所以,我的问题变成了处理异常的正确模式是什么?
在同步世界中,我对 _execSQL 和 _getCount 都无能为力,只能捕获 中的异常验证;自然而然地让异常冒泡。
但是,在异步世界中,我如何在不获得 'Unhandled Promise' 异常的情况下做同样的事情?
我是否一直坚持必须在所有关卡中捕获每个异步例程中的错误?
或者有没有更好的方法而不使用像 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
中,那么就去做吧:用 [=] 包围这个 await
13=]/catch
块和 "handle" 错误 catch
你认为最好的方式......不确定我在这里看到问题!