Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...