Tavados Tavados - 1 year ago 114
C# Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download