Search Unity

  1. Are you interested in providing feedback directly to Unity teams? Sign up to become a member of Unity Pulse, our new product feedback and research community.
    Dismiss Notice

Exception on main thread doesn't log to console

Discussion in 'Scripting' started by hk1ll3r, Jan 21, 2021.

  1. hk1ll3r


    Sep 13, 2018
    Part of my code was not running silently. I'm using the firebase SDK and think their helper functions are catching the exception without printing anything. Posting here to get feedback and also have somewhere on the internet this is being discussed. I'll write to firebase team as well.

    I attached the debugger and stepped through code until I found the line that is causing the issue. Commenting out the line will cause the program to run correctly. Upon inspection it turns out I have a null pointer exception in that line.

    The exceptions on background threads don't print to console. The problem here is that the exception, even though on main thread wasn't logging the error to console as it should.

    How do I know the code is running on the main thread? I print the
    Code (CSharp):
    1. Thread.CurrentThread.ManagedThreadId.ToString()
    before the faulty line and in Start() callbacks and make sure the id is the same.

    Here is the stack trace of the thread.
  2. hk1ll3r


    Sep 13, 2018
    I realized that since firebase uses tasks, it is expected that the exceptions are caught. I wrote a helper to print out the errors from the tasks. In cases where you expect task continuations to succeed, you can use this helper. It took me a full day to figure this out, so hopefully it will help somebody else.

    Code (CSharp):
    2.     public static class TaskExts {
    3.         public static void LogExceptionIfFaulted(this Task task) {
    4.             task.ContinueWithOnMainThread(t => {
    5.                 if (t.IsFaulted) {
    6.                     Debug.LogException(t.Exception.Flatten().InnerException);
    7.                 }
    8.             });
    9.         }
    10.     }
    Code (CSharp):
    1. FirebaseRemoteConfig.FetchAsync(TimeSpan.Zero).ContinueWithOnMainThread(task => {
    2.                 // custom code which may throw exceptions
    3. }).LogExceptionIfFaulted();
    Now if the task continuation fails, the exception will be printed to Unity console.