4

I am writing UI of an application using Haxe for CPP targets. I need to intercept haxe error/exceptions before it crashes the App.
Below is an example of code which crashes the application:

@:final private function callFoo(classA : IInterface) : Void
{
    if ((mClassLevelVariable != null) && (classA != mClassLevelVariable))
    {
        throw new Error("Can not work with " + Type.getClassName(Type.getClass((classA))));
    }
}  

I need to intercept the crash before error like given above crashes the application. Do we have any support in Haxe like Java provides Thread.UncaughtExceptionHandler?

Gama11
  • 31,714
  • 9
  • 78
  • 100
Alien Geography
  • 383
  • 1
  • 2
  • 14

1 Answers1

4

You could simply wrap your main() in a try-catch:

class Main {
    static function main() {
        try {
            entryPoint();
        } catch (e:Any) {
            // do something with e
        }
    }
}

That's pretty much how for instance OpenFL implements Flash's uncaught error event as well.

Note that not all exceptions can be caught this way in hxcpp. Null pointer exceptions for instance can only be caught if HXCPP_CHECK_POINTER is defined.

Gama11
  • 31,714
  • 9
  • 78
  • 100
  • exactly the kind of answer i was looking for. Suppose i want to crash the app after i've intercepted the error and done everything i needed, then how can we accomplish that? For example, i intercepted the exception/error then i logged something in server and then i want to crash the application. then how can we do that if we have this kind of try/catch block on the entryPoint? – Alien Geography Mar 25 '19 at 18:26
  • Just re-throw the error with `throw e;` - not sure if hxcpp allows preserving the callstack, but some platforms do: https://github.com/HaxeFoundation/haxe/issues/4159. – Gama11 Mar 25 '19 at 18:52