Created
March 29, 2021 01:26
-
-
Save d12/730884c63f53100c4ca15582e68b50eb to your computer and use it in GitHub Desktop.
A simple Unity exception handler that reports errors to a server. Handy for tracking down issues hit by end users.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class ExceptionManager : MonoBehaviour | |
{ | |
private const int ExceptionsPerCooldown = 5; | |
private const float CooldownTime = 5f; | |
private int _exceptionsLeftBeforeTimeout = ExceptionsPerCooldown; | |
private Coroutine _cooldownCoroutine; | |
private void OnEnable() | |
{ | |
Application.logMessageReceivedThreaded += LogReceived; | |
} | |
private void OnDisable() | |
{ | |
Application.logMessageReceivedThreaded -= LogReceived; | |
} | |
private void LogReceived(string condition, string stacktrace, LogType type) | |
{ | |
if (_exceptionsLeftBeforeTimeout <= 0) return; | |
if (type != LogType.Error && type != LogType.Exception) return; | |
SendExceptionToServer(condition, stacktrace, type); | |
_exceptionsLeftBeforeTimeout -= 1; | |
if (_exceptionsLeftBeforeTimeout <= 0 && _cooldownCoroutine == null) | |
{ | |
_cooldownCoroutine = StartCoroutine(EnableReportingCooldown()); | |
} | |
} | |
private void SendExceptionToServer(string condition, string stacktrace, LogType type) | |
{ | |
// Report to server | |
} | |
private IEnumerator EnableReportingCooldown() | |
{ | |
yield return new WaitForSeconds(CooldownTime); | |
_exceptionsLeftBeforeTimeout = ExceptionsPerCooldown; | |
_cooldownCoroutine = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment