Is it possible to catch all the unhandled exceptions in a centralized place?
i.e. let’s say that the game could through server connection exceptions in several places, I want them to be caught from an unique place, for example to show a message box.
3 Answers
3You can use Application.RegisterLogCallback to get everything that goes into the unity log - it gives you the type, the stack trace and the logging string of exceptions and, of course, a bunch of other things - would that help you?
using UnityEngine;
using System;
public class test : MonoBehaviour {
public string output = "";
public string stack = "";
void OnEnable() {
Application.RegisterLogCallback(HandleLog);
}
void OnDisable() {
Application.RegisterLogCallback(null);
}
void HandleLog(string logString, string stackTrace, LogType type) {
output = logString;
stack = stackTrace;
}
}
That sounds like a bad idea.
Nevertheless, these pages discuss some options:
- c# - How to implement one "catch'em all" exception handler with resume? - Stack Overflow
- http://mono-for-android.1047100.n5.nabble.com/Troubleshooting-an-ANR-Global-Exception-Handler-td5515296.html
- AppDomain.UnhandledException Event (System) | Microsoft Learn
- AppDomain.CurrentDomain.UnhandledException
That Stack Overflow thread is not primarily discussing the Mono runtime, so may not apply.
oh thanks for the answer...yeah in c# it is easy, but I was wondering how to do it in the Unity Environment. In a standard c# application I have the concept of mainform, which I do not have in Unity.
– sebas77
yes I thought about that, but I am not sure it is a good idea. I mean if I cannot use catch, I will not either use throw then. I could implement something on my own (like a messaging system that works in a similar way)
– sebas77Yeah, understood - thought it was worth pointing out.
– whydoidoitthank you a lot anyway :)
– sebas77I mark it as correct, because eventually it was a correct answer
– sebas77This was exactly what I was looking for. It is deprecated however, the new callback is "Application.logMessageReceived". So you would do: private void Awake(){ Application.logMessageReceived += handleUnityLog; } // then private void handleUnityLog(string logString, string stackTrace, LogType type) { // do stuff }
– LiterallyJeff