Search Issue Tracker

Active

Votes

20

Found in

2019.4

2020.3

2021.3

2021.3.0f1

2022.1

2022.2

Issue ID

1427315

Regression

No

Exceptions are not logged when thrown from "async Task"

Scripting

-

How to reproduce:
1. Open project "LogsInAsync.zip"
2. In the Hierarchy window select "GameObject" GameObject
3. In the Inspector window press on three dots of the script Component and choose "Call Async Methods"
4. Observe the Console window

Expected result: Exception is logged
Actual result: Exception is not logged

Reproducible with: 2019.4.39f1, 2020.3.35f1, 2021.3.3f1, 2022.1.2f1, 2022.2.0a15

Reproducible on: macOS 11.6 (Intel)

Comments (3)

  1. Tortuap

    Jan 24, 2024 14:57

    I don't know the exact issue described in this ticket, but void async, as well as non awaited Awaitable are not logging Exception, and this is the behaviour to be expected, as the Exception is trapped by the Awaitable, and thus never to be logged by anyone.

    One correct way to get exceptions logged is to use async event methods ( async Start, async Awake, etc. ) like so:

    async Awaitable TestAsync ()
    {
    throw new Exception ( "Test of exception" );
    await Awaitable.NextFrameAsync ();
    }

    protected async void Start ()
    {
    await TestAsync (); // exception is caught & logged by Unity code that started async Start
    }

    Another way, if called in a non async method, is to do :

    protected void Start ()
    {
    TestAsync ().GetAwaiter ().GetResult (); // GetResult executes PropagateExceptionAndRelease which raise the exception trapped in the Awaitable
    }

    Finally, you could, but I don't recommend, use an extension method like:

    public static class AwaitableExtensions
    {
    public static Exception GetException ( this Awaitable awaitable )
    {
    var edi = awaitable.GetFieldValue<ExceptionDispatchInfo> ( "_exceptionToRethrow" );
    return edi.SourceException;
    }
    }

    ...
    var asyncOpe = TestAsync (); // exception is kept in the Awaitable, and won't be logged
    ...
    if ( asyncOpen.IsCompleted ) // exception also "complete" the Awaitable
    {
    var e = asyncOpe.GetException();
    if ( e != null ) throw e; // propagate it yourself
    }
    ...

  2. Hoodrij

    Aug 07, 2023 18:58

    TaskScheduler.UnobservedTaskException solution is not working with Awaitable.

  3. bob_ross_tree

    Sep 09, 2022 13:34

    In case anybody needs a temporary solution until unity fixes it.
    The following code should should catch these exceptions.

    System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (_, e) => Debug.LogException(e.Exception);

Add comment

Log in to post comment

All about bugs

View bugs we have successfully reproduced, and vote for the bugs you want to see fixed most urgently.