Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all exception in Unity

I've got a Unity mobile game in the app stores and I've got a function that sends emails from the players to my server, to notify me that stuff happened, that is not supposed to happen. If e.g. a try that I wrote fails, I send myself an email to see, that there must be a bug.

Is it possible, to build something like an OnException handler, that sends me an email on every exception that occurs, including code I didn't write? Some exceptions may come from plugins that I use, so I would like to have some sort of Listener, that does stuff whenever any sort of exception get's called.

Is that possible?

like image 233
Tavados Avatar asked Jul 13 '26 07:07

Tavados


1 Answers

You can't catch all other exceptions in other plugins. Unity does that in the background and Unity gives you API to receive the exceptions it caught:

Newer version of Unity:

void OnEnable()
{
    Application.logMessageReceived += LogCallback;
}

//Called when there is an exception
void LogCallback(string condition, string stackTrace, LogType type)
{
    //Send Email
}

void OnDisable()
{
    Application.logMessageReceived -= LogCallback;
}

Older version of Unity:

void OnEnable()
 {
     Application.RegisterLogCallback(LogCallback);
 }

 //Called when there is an exception
 void LogCallback(string condition, string stackTrace, LogType type)
 {
     //Send Email
 }

 void OnDisable()
 {
     Application.RegisterLogCallback(null);
 }

There is also logMessageReceivedThreaded.

EDIT:

Stacktrace issue:

If the stackTrace parameter is empty then you can use the System.Diagnostics.StackTrace class to manually retrieve the stacktrace yourself while still inside the LogCallback function. For example,

void LogCallback(string condition, string stackTrace, LogType type)
{
    //Send Email

    System.Diagnostics.StackTrace sTrace = new System.Diagnostics.StackTrace();
    Debug.Log(sTrace.ToString());
}
like image 162
Programmer Avatar answered Jul 15 '26 19:07

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!