Handling StoreKit Errors

Sam Mejlumyan avatar
Sam Mejlumyan

The error state is one of the five UI states. It is pretty important for users’ experience and satisfaction. If you don’t handle errors, it will be the main reason for users to lose control and as a consequence –  reduction in retention or even deletion of the app. 

Error handling is more important when you work with dependencies, especially when working with a library like StoreKit. In general, StoreKit is a black-box in which anything can happen. In this short article, we will explore how to handle failed transactions and give appropriate error messages to the user as a feedback.

NSError Overview

I just want to remind you how NSError works. We will need it below. Any error that happens on iOS includes error domain, domain-specific error code, and additional information specific for application. So, for us the most important fields are:

Variety of errors

Errors associated with payments, store products, and cloud services occur with the domain model SKErrorDomain and error codes SKError.Code. The entire list of errors includes more than 15 options, you can find them in this documentation. In addition to SKErrorDomain errors, there may be network problems that occur in the `NSURLErrorDomain` domain model. Let’s handle all of them. 

Handling StoreKit errors

For error handling, we need to implement two methods of the SKRequestDelegate delegate.

optional func request(_ request: SKRequest, didFailWithError error: Error)

This is an optional method that receives errors from SKRequest. It is important to keep in mind that when these errors occur, ‘(void) requestDidFinish: (SKRequest *) request‘ will not be called.

The second point of failure is transaction processing, here errors are quite varied and can be associated with both the fact that the user canceled the operation, and with the restriction of rights under parental control, for example. To receive errors when working with transactions, it is necessary to separately process the transaction status SKPaymentTransactionStateFailed.

```objective-c
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue
 updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
  for (SKPaymentTransaction *transaction in transactions) {
	  switch (transaction.transactionState) {
	    case SKPaymentTransactionStatePurchasing:
	      break;
	    case SKPaymentTransactionStatePurchased:
	      // implement handling purchased state
	      // [self handlePurchasedTransaction:transaction];
	      break;
	    case SKPaymentTransactionStateFailed:
	      [self handleFailedTransaction:transaction];
	      break;
	    case SKPaymentTransactionStateRestored:
	      // implement handling restored state
	      // [self handlePurchasedTransaction:transaction];
	      break;
	    default:
	      break;
	  }
  }
}
```

 Method `handleFailedTransaction`:

```
- (void)handleFailedTransaction:(SKPaymentTransaction *)transaction {
  NSError *error = transaction.error;
  
  if (error && [[error domain] isEqualToString:SKErrorDomain]) {    
      switch (error.code) {
        case SKErrorUnknown:
          // Error code indicating that an unknown or unexpected error occurred.
          break;
        case SKErrorClientInvalid:
          // Error code indicating that the client is not allowed to perform the attempted action.
          break;
        case SKErrorPaymentCancelled:
          // Error code indicating that the user canceled a payment request.
          break;
        case SKErrorStoreProductNotAvailable:
          // Error code indicating that the requested product is not available in the store.
          break;
        case SKErrorPaymentNotAllowed:
          // Error code indicating that the user is not allowed to authorize payments.
          break;
        case SKErrorPaymentInvalid:
          // Error code indicating that one of the payment parameters was not recognized by the App Store.
          break;
        // Belowe codes available on different iOS
        case 6:
          // SKErrorCloudServicePermissionDenied
          // Error code indicating that the user has not allowed access to Cloud service information.
          break;
        case 7:
          // SKErrorCloudServiceNetworkConnectionFailed
          // Error code indicating that the device could not connect to the network.
          break;
        case 8:
          // SKErrorCloudServiceRevoked
          // Error code indicating that the user has revoked permission to use this cloud service.
          break;
        case 9:
          // SKErrorPrivacyAcknowledgementRequired
          // Error code indicating that the user has not yet acknowledged Apple’s privacy policy for Apple Music.
          break;
        case 10:
          // SKErrorUnauthorizedRequestData
          // Error code indicating that the app is attempting to use a property for which it does not have the required entitlement.
          break;
        case 11:
          // SKErrorInvalidOfferIdentifier
          // The specified subscription offer identifier is not valid
        case 12:
          // SKErrorInvalidSignature
          // The cryptographic signature provided is not valid
          break;
        case 13:
          // SKErrorMissingOfferParams
          // One or more parameters from SKPaymentDiscount is missing
          break;
        case 14:
          // SKErrorInvalidOfferPrice
          // The price of the selected offer is not valid (e.g. lower than the current base subscription price)
          break;
      }
  } else if (error && [[error domain] isEqualToString:NSURLErrorDomain]) {
    switch (error.code) {
      case NSURLErrorNotConnectedToInternet:
        // A network resource was requested, but an internet connection has not been established and can’t be established automatically.
        break;
      default:
       // Handle other network errors here
      break;
    }
  }
  
}
```

What to do about it?

There are a lot of types of errors, so I‘d recommend dividing them into several groups:

  • external, which cannot be influenced in any way, for example, network problems
  • request errors such as incorrect product ID
  • user side errors such as canceling an operation or an unverified account

External errors

For such errors, an alert about the error itself is enough, as well as a repeat button for starting purchasing again. For example, if there is no Internet or an error occurs when connecting to the App Store.

Request errors

This is a group of errors that can cause the greatest damage to the product conversions, as they are system problems, for example, `SKErrorStoreProductNotAvailable` or `SKErrorInvalidOfferPrice`. Errors of this group must be covered with additional logging, with ability to remotely catch them on the server and fix them.

User side errors 

This group of errors is directly related to the user’s state, for example, `SKErrorPrivacyAcknowledgmentRequired`

Correct error handling within the application is a very important part of the user experience. First of all, I would recommend implementing the error and (not too sure, would you say “implementing the error AT the loading state”, since both have to occur simultaneously)  the loading state and then start implementing the main (content) state. 

mobile-subscription-analytics-qonversion