Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Exception on main thread doesn't log to console

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

  1. hk1ll3r

    hk1ll3r

    Joined:
    Sep 13, 2018
    Posts:
    88
    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.
    callstack.png
     
  2. hk1ll3r

    hk1ll3r

    Joined:
    Sep 13, 2018
    Posts:
    88
    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):
    1.  
    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.     }
    11.  
    usage:
    Code (CSharp):
    1. FirebaseRemoteConfig.FetchAsync(TimeSpan.Zero).ContinueWithOnMainThread(task => {
    2.                 // custom code which may throw exceptions
    3. }).LogExceptionIfFaulted();
    4.  
    Now if the task continuation fails, the exception will be printed to Unity console.
     
    s-saens and fredsandstorm like this.
  3. s-saens

    s-saens

    Joined:
    Aug 14, 2019
    Posts:
    8
    Thanks! It really helped me.