1

在我的应用程序的某些点,我有一个 try-catch 块,例如:这发生在不在显示列表中的类(不是Sprites,也不是任何类型的DisplayObject),而是扩展EventDispatcher。这些类驻留在外部加载的 SWF 中(以防万一)。

try {
    ... some logic that may throw Error
} catch (e:Error) {
    var errorEvent:ErrorEvent = new ErrorEvent(ErrorEvent.ERROR, true);
    errorEvent.text = e.getStackTrace();
    dispatchEvent(errorEvent);
}

在根类中,这就是我所拥有的:

loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtErrorHandler);
loaderInfo.uncaughtErrorEvents.addEventListener(ErrorEvent.ERROR, onErrorEventHandler);
stage.addEventListener(ErrorEvent.ERROR, onErrorEventHandler);

protected function onUncaughtErrorHandler(event:UncaughtErrorEvent):void
{
    var message:String; 
    if (event.error is Error) {
        message = event.error.getStackTrace();
    } else if (event.error is ErrorEvent) {
        message = ErrorEvent(event.error).text;
    } else {
        message = event.error.toString(); 
    }

    trace(message);
}

protected function onErrorEventHandler(event:ErrorEvent):void
{
    trace(event.text);
}

两个处理程序都没有被调用,但是这些错误事件会冒泡,我在控制台中看到它们,并且在调试模式下作为弹出窗口,但是我如何在根类中收听它们?

我这样做是因为我不希望错误中断主线程或特定业务逻辑的执行。

4

2 回答 2

2

我认为您正在寻找的是未捕获错误事件的侦听器。这是在根类中添加它的示例:

this.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onGlobalErrors);

由 LDMS 编辑

以下在 FlashPro 中有效:

loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR,function(e:Event){
    trace("I Caught an Error");
});

var err:ErrorEvent = new ErrorEvent(ErrorEvent.ERROR,true);

var obj:EventDispatcher = new EventDispatcher();

obj.dispatchEvent(err);
于 2014-09-18T15:56:21.007 回答
0

如果您的班级在舞台上,您可以为ErrorEvent.ERROR舞台添加事件侦听器。任何分派的事件都将stage通过其所有父级到达。

代码示例:

// some initialize
stage.addEventListener("lol", lolHandler);
// dispatching
private function button1_clickHandler(event:MouseEvent):void
{
    // second parameter responsible for bubbling and MUST be true
    dispatchEvent(new Event("lol", true)); // on mouseClick we dispatch custom event
}

private function lolHandler(event:Event):void
{
     trace("We got it! Lol!);
}

PS评论中的文章真的很有用。推荐阅读。

// 更新

替代变体可以是从某个单例中调度事件。例如:

    public class ErrorHandler extends EventDispatcher {
        private static var _instance:ErrorHandler;

        public static function get instance():ErrorHandler {
            if (!_instance)
                _instance = new ErrorHandler(new PrivateConstructor());

            return _instance;
        }

        public function ErrorHandler(value:PrivateConstructor) {
            addEventListener(ErrorEvent.ERROR, errorHandler);
        }

        private function errorHandler(event:ErrorEvent):void {
            // some code
        }
    }
}
class PrivateConstructor {}

.... and dispatching
ErrorHandler.instance.dispatchEvent(new ErrorEvent());
于 2014-09-18T15:17:41.933 回答