docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Synchronous errors thrown by async methods

    Handle synchronous errors thrown by asynchronous methods in the Instant Games SDK.

    To handle asynchronous errors only, refer to Asynchronous errors.

    Async methods throwing JsException and APIError

    Asynchronous methods can throw synchronous exceptions, which occur when the method is called, and asynchronous exceptions, which occur when the returned task is awaited.

    For example, the endpoint FBInstant.Player.SetDataAsync throws JsException synchronously if the string provided isn't valid JSON:

    // throws JsException:
    var task = FBInstant.Player.SetDataAsync("{ invalid JSON }");
    

    But it can also throw APIError asynchronously for a variety of reasons, for example, if a previous call to the endpoint hasn't yet completed:

    // doesn't throw:
    var task = FBInstant.Player.SetDataAsync("{ \"myKey\": \"my value\" }");
    
    // throws APIError with ErrorCode.PENDING_REQUEST:
    await task;
    

    Error handling

    To handle both synchronous and asynchronous errors, you can do either of the following:

    • Use separate try blocks for the two phases of execution (calling the function, then awaiting the task).

    • Combine the two phases in a single expression that both calls the function and awaits the result, using a single try block and multiple catch blocks:

      try
      {
          await FBInstant.Player.SetDataAsync(someString);
      }
      catch (APIError e)
      {
          // handle the various kinds of APIError the endpoint might throw
      }
      catch (JsException e)
      {
          // handle invalid JSON
      }
      
      Note

      In this example, the catch block for APIError must precede that for JsException because APIError derives from JsException.

    Additional resources

    • Error handling
    • Synchronous errors
    • Asynchronous errors
    In This Article
    Back to top
    Copyright © 2025 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)