Handling errors
Make debugging easier and respond gracefully to runtime errors.
Types of exceptions
Sphere Kit throws exceptions that fall into 6 types:
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.
Wrap calls to Sphere Kit with a try-catch statement. When you have a piece of code inside a
tryblock, you expect it to run smoothly. However, if an error occurs, thecatchblock 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
}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
}
}Handle the error accordingly. All errors have a
Codeattribute (exceptInternalServerExceptionandRateLimitException) which is an enum with the error code, and aMessageattribute which is a descriptive message for the error.
Last updated