未验证 提交 24d506ac 编写于 作者: G Gcaufy 提交者: GitHub

Fix async error handler (#1968)

* fix: fixed to handle async error

* 0.39.30

* 0.39.31

* fix: code fix
Co-authored-by: Huan (李卓桓)'s avatarHuan (李卓桓) <zixia@zixia.net>
上级 4472daa0
......@@ -149,6 +149,42 @@ test('on(event, Function)', async t => {
})
test('test async error', async (t) => {
// Do not modify the gloabl Wechaty instance
class MyWechatyTest extends Wechaty {}
const EXPECTED_ERROR = new Error('test')
const bot = new MyWechatyTest({
puppet: new PuppetMock(),
})
const asyncErrorFunction = function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
reject(EXPECTED_ERROR)
}, 100)
// tslint ask resolve must be called,
// so write a fasly value, so that it never called
if (+new Date() < 0) {
resolve()
}
})
}
bot.on('message', async () => {
await asyncErrorFunction()
})
bot.on('error', (e) => {
t.ok(e.message === EXPECTED_ERROR.message)
})
bot.emit('message', {} as any)
await bot.stop()
})
test('use plugin', async (t) => {
// Do not modify the gloabl Wechaty instance
......
......@@ -585,7 +585,7 @@ export class Wechaty extends EventEmitter implements Sayable {
hotImport(absoluteFilename)
.then((func: AnyFunction) => super.on(event, (...args: any[]) => {
try {
func.apply(this, args)
return func.apply(this, args)
} catch (e) {
log.error('Wechaty', 'addListenerModuleFile(%s, %s) listener exception: %s',
event, modulePath, e,
......@@ -610,15 +610,22 @@ export class Wechaty extends EventEmitter implements Sayable {
private addListenerFunction (event: WechatyEventName, listener: AnyFunction): void {
log.verbose('Wechaty', 'addListenerFunction(%s)', event)
const handleError = (e: Error, type = '') => {
log.error('Wechaty', 'addListenerFunction(%s) listener %sexception: %s', event, type, e)
this.emit('error', e)
}
/**
* We use `super.on()` at here to prevent loop
*/
super.on(event, (...args: any[]) => {
try {
listener.apply(this, args)
const result = listener.apply(this, args)
if (result && result.catch && typeof result.catch === 'function') {
result.catch((e: Error) => handleError(e, 'async'))
}
} catch (e) {
log.error('Wechaty', 'addListenerFunction(%s) listener exception: %s', event, e)
this.emit('error', e)
handleError(e)
}
})
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册