¿Cómo detectar todas las excepciones en Flex?


Cuando corro una aplicación Flex en debug flash player, aparece una excepción tan pronto como ocurre algo inesperado. Sin embargo, cuando un cliente utiliza la aplicación, no utiliza debug flash player. En este caso, no aparece una ventana emergente de excepción, pero la interfaz de usuario no funciona.

Así que por razones de compatibilidad, me gustaría detectar cualquier excepción que pueda ocurrir en cualquier lugar de la interfaz de usuario de Flex y presentar un mensaje de error en una ventana emergente interna de Flex. Usando Java me gustaría simplemente encapsular todo el código de la interfaz de usuario en un bloque try / catch, pero con aplicaciones MXML en Flex no sé, donde podría realizar un try/catch tan general.

Author: Yaba, 2008-09-19

9 answers

No hay forma de ser notificado sobre excepciones no capturadas en Flex 3. Adobe es consciente del problema, pero no se si planean crear una solución.

La única solución tal como está es poner try/catch en lugares lógicos y asegurarse de que está escuchando el evento de ERROR (o FALLA para los servicios web) para cualquier cosa que los envíe.

Edit: Además, en realidad es imposible detectar un error generado por un controlador de eventos. He registrado un error en el Sistema de Errores de Adobe.

Actualización 2010-01-12: El manejo global de errores ahora está soportado en Flash 10.1 y AIR 2.0 (ambos en beta), y se logra suscribiendo el evento UNCAUGHT_ERROR de LoaderInfo.uncaughtErrorEvents. El siguiente código se toma de la muestra de código en livedocs:

public class UncaughtErrorEventExample extends Sprite
{
    public function UncaughtErrorEventExample()
    {
        loaderInfo.uncaughtErrorEvents.addEventListener(
            UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
    }

    private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
    {
        if (event.error is Error)
        {
            var error:Error = event.error as Error;
            // do something with the error
        }
        else if (event.error is ErrorEvent)
        {
            var errorEvent:ErrorEvent = event.error as ErrorEvent;
            // do something with the error
        }
        else
        {
            // a non-Error, non-ErrorEvent type was thrown and uncaught
        }
    }
 50
Author: Richard Szalay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-09 01:10:47

Hay una solicitud de error/característica para esto en el sistema de administración de errores de Adobe. Vota por él si es importante para ti.

Http://bugs.adobe.com/jira/browse/FP-444

 9
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-04 15:28:15

Funciona en Flex 3.3.

 if(loaderInfo.hasOwnProperty("uncaughtErrorEvents")){
    IEventDispatcher(loaderInfo["uncaughtErrorEvents"]).addEventListener("uncaughtError", uncaughtErrorHandler);
 }
 4
Author: Termininja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-17 10:31:40

Tenga en cuenta que el error FP-444 (arriba) enlaza con http://labs.adobe.com/technologies/flashplayer10/features.html#developer que desde octubre de 2009 muestra que esto será posible a partir de la 10.1, que actualmente, el 28 de octubre de 2009 aún no se ha lanzado, así que supongo que veremos si eso es cierto cuando se lance

 3
Author: Peter V. Mørch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-28 12:09:34

Alternativa a la respuesta aceptada, usando try-catch. Más lento, pero más sencillo de leer, creo.

try {
    loaderInfo.uncaughtErrorEvents.addEventListener("uncaughtError", onUncaughtError);
} catch (e:ReferenceError) {
    var spl:Array = Capabilities.version.split(" ");
    var verSpl:Array = spl[1].split(",");

    if (int(verSpl[0]) >= 10 &&
        int(verSpl[1]) >= 1) {
        // This version is 10.1 or greater - we should have been able to listen for uncaught errors...
        d.warn("Unable to listen for uncaught error events, despite flash version: " + Capabilities.version);
    }
}

Por supuesto, necesitarás usar un playerglobal 10.1 actualizado.swc para compilar este código con éxito: http://labs.adobe.com/downloads/flashplayer10.html

 3
Author: aaaidan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-11 04:29:54

Estoy usando flex 4. Probé loaderInfo.UncaughtErrorEvents, pero LoaderInfo no se inicializó, por lo que me dio un error de referencia nulo. Luego intenté root.loaderInfo.UncaughtErrorEvents y la misma historia. Probé sprite.root.UncaughtErrorEvents, pero no había ningún objeto sprite, creé uno, pero no funcionó. Finalmente lo intenté

SystemManager.LoaderInfo.Eventos de terror sin chicas.addEventListener (UncaughtErrorEvent.UNCAUGHT_ERROR, globalUnCaughtErrorHandler.hanleUnCaughtError);

Y adivina qué, funciona como magia. compruebe esto

 3
Author: Rose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-05 14:11:48

Funciona en Flex 3.5 y flash player 10:

<?xml version="1.0" encoding="utf-8"?>

        protected function application1_addedToStageHandler(event:Event):void{              
            if(loaderInfo.hasOwnProperty("uncaughtErrorEvents")){
                IEventDispatcher(loaderInfo["uncaughtErrorEvents"]).addEventListener("uncaughtError", uncaughtErrorHandler);
            }

            sdk.text = "Flex " + mx_internal::VERSION;
        }

        private function uncaughtErrorHandler(e:*):void{
            e.preventDefault();

            var s:String;

            if (e.error is Error)
            {
                var error:Error = e.error as Error;
                s = "Uncaught Error: " + error.errorID + ", " + error.name + ", " + error.message;
            }
            else
            {
                var errorEvent:ErrorEvent = e.error as ErrorEvent;
                s = "Uncaught ErrorEvent: " + errorEvent.text;
            }

            msg.text = s;
        }

        private function unCaught():void
        {
            var foo:String = null;
            trace(foo.length);
        }
    ]]>
</mx:Script>
<mx:VBox>
    <mx:Label id="sdk" fontSize="18"/>
    <mx:Button y="50" label="UnCaught Error" click="unCaught();" />
    <mx:TextArea id="msg" width="180" height="70"/>
</mx:VBox>

Gracias

 3
Author: Jefferson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-06 13:18:27

Adjunté el receptor de eventos a la 'raíz', que funcionó para mí:

sprite.root.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);

En debug Flash Player esto seguirá siendo un error, pero en la versión sin depuración el error aparecerá en el cuadro de diálogo de Flash Player, y luego el controlador responderá. Para evitar que aparezca el cuadro de diálogo, agregue:

event.preventDefault();

Así que:

    private function onUncaughtError(event:UncaughtErrorEvent):void
    {
        event.preventDefault();
        // do something with this error
    }

Estaba usando esto en AIR, pero supongo que también funciona para proyectos AS3 estándar.

 2
Author: neave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-14 17:06:08

Ahora puedes, usando la información del cargador:

Http://www.adobe.com/devnet/flex/articles/global-exception-handling.html

Checkout: LoaderInfo.Eventos de terror sin chicas.addEventListener (UncaughtErrorEvent.En este caso, el valor de la imagen es el mismo que el valor de la imagen.]}

private function onUncaughtError(e:UncaughtErrorEvent):void
{
    // Do something with your error.
}
 0
Author: Pablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-04 19:21:29