在 Unity 中捕获所有异常 [英] Catch all exception in Unity

查看:150
本文介绍了在 Unity 中捕获所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用商店中有一款 Unity 手机游戏,我有一个功能可以将玩家的电子邮件发送到我的服务器,以通知我发生了不应该发生的事情.如果例如我写的一个 try 失败了,我给自己发了一封电子邮件,看看肯定有错误.

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.

是否有可能构建一个类似于 OnException 处理程序的东西,它会就发生的每个异常向我发送一封电子邮件,包括我没有编写的代码?一些异常可能来自我使用的插件,所以我想要某种侦听器,它可以在调用任何类型的异常时执行.

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.

这可能吗?

推荐答案

不能捕获其他插件中的所有其他异常.Unity 在后台执行此操作,Unity 为您提供 API 以接收它捕获的异常:

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:

较新版本的 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;
}

旧版 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);
 }

还有 logMessageReceivedThreaded.

编辑:

堆栈跟踪问题:

如果 stackTrace 参数为空,那么您可以使用 System.Diagnostics.StackTrace 类在 LogCallback 内部手动检索堆栈跟踪代码>功能.例如,

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

这篇关于在 Unity 中捕获所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆