Handling errors

Make debugging easier and respond gracefully to runtime errors.

Types of exceptions

Sphere Kit throws exceptions that fall into 6 types:

Exception type
Meaning

BadRequestException

The request was not formatted properly or certain conditions for executing the request was not met.

AuthenticationException

There was a problem authenticating the request (e.g. player not signed in).

ForbiddenException

The player was not authorised to execute the request.

NotFoundException

The resource requested in the request could not be found.

RateLimitException

There have been too many requests made and you need to wait a while before making new requests.

InternalServerException

An internal server error has occurred in Sphere Kit and the request should be attempted later.

Identifying and handling exceptions

It is very important to handle exceptions so that your game does not crash when they occur. Moreover, handling exceptions correctly also helps you find the causes to bugs easier.

The possible exceptions for each method are described in the class references, or when the methods have hyperlinks.

  1. Wrap calls to Sphere Kit with a try-catch statement. When you have a piece of code inside a try block, you expect it to run smoothly. However, if an error occurs, the catch block is triggered, allowing you to manage the error gracefully instead of crashing the program.

try
{
    // Code that might throw an exception
}
catch (Exception e)
{
    // Code to handle the exception
}
  1. Identify the type of error. This will allow you to update the UI accordingly or perform additional functions. In this example,

try
{
    // Code that might throw an exception
}
catch (Exception e)
{
    switch (e)
    {
        case BadRequestException badRequestException:
            Debug.LogError($"Bad Request: {badRequestException.Code} - {badRequestException.Message}");
            break;
        case AuthenticationException authenticationException:
            Debug.LogError($"Authentication Exception: ${authenticationException.Code} - {authenticationException.Message}");
            break;
        // Handle other exceptions as needed
    }
}
  1. Handle the error accordingly. All errors have a Code attribute (except InternalServerException and RateLimitException) which is an enum with the error code, and a Message attribute which is a descriptive message for the error.

Last updated