# Handle errors

Show the merchant a clear message for every way an app switch can fail, including error responses, voided sales, and missing returns.

**Prerequisites:** [Authentication](/api/authentication) · [Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale)

Errors can occur from when you pair your app to when you get the result of a sale. Mobile Sync doesn't show the merchant a message when an error occurs, so your app must show one. To help merchants, program your app to recognize each type of error and show a message that tells the merchant what to do next.

The following types of error can occur:

- [The reader identifier is out of date.](#the-reader-identifier-is-out-of-date)
- [The sale doesn't start on Mobile Sync.](#the-sale-doesnt-start-on-mobile-sync)
- [Mobile Sync returns an error.](#mobile-sync-returns-an-error)
- [The sale is voided or doesn't complete.](#the-sale-is-voided-or-doesnt-complete)
- [You can't confirm the result.](#you-cant-confirm-the-result)

**Note:** The code snippets on this page use placeholder functions for your app's own interface. Replace them with your own code:

- `showMessage(_:)` shows a message to the merchant.
- `askToPairAgain()` asks the merchant to pair again.
- `showCheckStatusButton()` shows a **Check status** button. When the merchant selects the button, call the [`checkStatus()`](#check-the-status-again) function.

The code also uses the variables that you set in [Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale), such as `isWaitingForSaleReturn` and `pendingSale`, and the `pair` and `unpair` functions from [Connect your app to Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync).

<a id="the-reader-identifier-is-out-of-date"></a>
## The reader identifier is out of date

If the reader identifier is out of date, your app must pair with Mobile Sync again. The reader identifier becomes out of date when:

- Our gateway doesn't recognize the reader identifier, for example, the merchant reinstalled Mobile Sync.
- Mobile Sync returns `notProvisioned` because it was reset.
- Mobile Sync is no longer installed, so `canOpenURL` returns `false`.

Tell the merchant that they need to pair again, and never delete the stored reader identifier without telling them. When the merchant agrees, use the following code to delete the old reader identifier and send a new pairing request.

```swift
/// Call when the merchant agrees to pair again.
func pairAgain(openURL: (URL) -> Void) {
    unpair()              // forget the old reader identifier, and disable the Pay button
    pair(openURL: openURL)
}
```

<a id="the-sale-doesnt-start-on-mobile-sync"></a>
## The sale doesn't start on Mobile Sync

A sale doesn't start if [Mobile Sync isn't ready](#mobile-sync-isnt-ready), or if [our gateway rejects your request](#our-gateway-rejects-your-request). If our gateway rejects your request, [Mobile Sync waits for a request that isn't coming](#mobile-sync-waits-for-a-request-that-isnt-coming).

<a id="mobile-sync-isnt-ready"></a>
### Mobile Sync isn't ready

When Mobile Sync isn't ready, `AppSwitchTransaction.run` stops and throws an `AppSwitchError`. The App Switch Kit doesn't send your request.

| **Error** | **Cause** | **What to show the merchant** |
| --- | --- | --- |
| `wsUnavailable` | Mobile Sync couldn't connect to our gateway, for example, because the iPhone is offline. | Check the internet connection, and then try again. |
| `readerUnavailable` | The card reader in Mobile Sync couldn't start. | Open Mobile Sync to see the details. |
| `readyTimeout` | Mobile Sync didn't send its ready signal within 30 seconds. | Try again. |

<a id="our-gateway-rejects-your-request"></a>
### Our gateway rejects your request

If our gateway rejects your request, `run` also throws the error. For example, our gateway might reject the request because the amount isn't valid, or because it [doesn't recognize the reader identifier](#the-reader-identifier-is-out-of-date).

Program your app to handle the errors that `run` throws and shows the merchant a message. The code in [Step 3 of Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale#step-3-switch-to-mobile-sync-and-send-the-request) calls it when the task throws an error.

If our gateway rejected your request, Mobile Sync is already open and waiting. The code tells Mobile Sync that no request is coming, so that Mobile Sync returns to your app immediately. For more information, go to [Tell Mobile Sync that your request failed](#tell-mobile-sync-that-your-request-failed).

<a id="example-code"></a>
#### Example code

```swift
import AppSwitchGatewayReference
import AppSwitchOrchestration
import Foundation

/// True when our gateway doesn't recognize the reader identifier that your app stored.
func isUnknownDevice(_ error: Error) -> Bool {
    if case GatewayError.http(let status, _) = error { return status == 404 }
    return false
}

/// Called by Run a sale, Step 3 when the task throws an error.
func handleStartError(_ error: Error) {
    // Your app canceled the sale. See Cancel a sale.
    if error is CancellationError || (error as? URLError)?.code == .cancelled { return }

    isWaitingForSaleReturn = false

    // Mobile Sync wasn't ready, so the kit didn't send your request.
    if let switchError = error as? AppSwitchError {
        switch switchError {
        case .wsUnavailable:
            showMessage("Check the internet connection, and then try again.")
        case .readerUnavailable:
            showMessage("Open Mobile Sync to see the details.")
        case .readyTimeout:
            showMessage("Mobile Sync didn't respond. Try again.")
        }
        return
    }

    // Our gateway rejected your request. Tell Mobile Sync that no request is coming.
    reportPostFailure()

    if isUnknownDevice(error) {
        askToPairAgain()                       // pair with Mobile Sync again
    } else {
        showMessage(error.localizedDescription)
    }
}
```

<a id="mobile-sync-waits-for-a-request-that-isnt-coming"></a>
### Mobile Sync waits for a request that isn't coming

Our App Switch Kit and our gateway can accept the switch and bring Mobile Sync online, and then our gateway rejects your request. If this happens, Mobile Sync waits for the sale and the iPhone stays on the Mobile Sync screen until the instruction timeout ends. To shorten the wait, you can:

- [Change the instruction timeout](#change-the-instruction-timeout).
- [Tell Mobile Sync that your request failed](#tell-mobile-sync-that-your-request-failed).

<a id="change-the-instruction-timeout"></a>
#### Change the instruction timeout

After Mobile Sync is ready, it waits 30 seconds for your request. If no request arrives, Mobile Sync returns to your app with `status=timeout`.

If you want to change the timeout for a sale, for example, if you encounter slow network conditions, add `instructionTimeoutInSeconds` to the switch URL. Mobile Sync accepts only values between `1` and `300` seconds.

```swift
import AppSwitchContract
import Foundation

func switchURL(timeoutSeconds: Int) -> URL? {
    guard let base = AppSwitchURL.switchURL(targetScheme: MobileSync.scheme, callback: Callback.sale),
          var components = URLComponents(url: base, resolvingAgainstBaseURL: false)
    else { return nil }

    var items = components.percentEncodedQueryItems ?? []
    items.append(URLQueryItem(name: AppSwitchURL.instructionTimeoutQueryItem, value: String(timeoutSeconds)))
    components.percentEncodedQueryItems = items
    return components.url
}
```

<a id="tell-mobile-sync-that-your-request-failed"></a>
#### Tell Mobile Sync that your request failed

If your request fails, send the `com.payroc.appswitch.instruction.failed` signal. Mobile Sync then returns to your app immediately with `status=failed`. The signal has no payload, and Mobile Sync doesn't confirm that it received it. The `handleStartError` function in [Our gateway rejects your request](#our-gateway-rejects-your-request) calls the following code.

```swift
import AppSwitchContract

/// Tell Mobile Sync that no request is coming.
func reportPostFailure() {
    AppSwitchInstructionSignalName.post(AppSwitchInstructionSignalName.instructionFailed)
}
```

<a id="mobile-sync-returns-an-error"></a>
## Mobile Sync returns an error

If there is an error with Mobile Sync, Mobile Sync can switch back to your app with an `error` query item in the return URL. This can happen in the response to a pairing request and in the response to a sale or a signature capture.

Mobile Sync can return the following errors in the response to a [pairing request](#a-pairing-response-contains-an-error) or a [sale request](#a-sale-response-contains-an-error):

| **Error** | **What it means** | **What your app does** |
| --- | --- | --- |
| `unsupportedScheme` | Your app opened a Mobile Sync scheme that isn't one of the switch schemes that you configured in your app. | Correct the scheme in your app. This is a problem with your integration, so you shouldn't see it in production. |
| `notProvisioned` | A sale reached a version of the Mobile Sync app that is new or was reset, so the reader identifier that your app stored is out of date. | [Pair your app with Mobile Sync again](#the-reader-identifier-is-out-of-date). |
| `standaloneMode` | Mobile Sync is set up, but it's in Standalone mode, so it can't receive requests from Payroc Cloud. Mobile Sync returns this for a sale, a signature capture, and a pairing request. | Keep the pairing, because the reader identifier doesn't change when the merchant switches mode. Ask the merchant to switch Mobile Sync back to Payroc Cloud in its App settings. |
| `modeSwitchInProgress` | A pairing request reached Mobile Sync while the merchant is changing Mobile Sync's mode. | Keep the pairing. Ask the merchant to finish the mode switch in Mobile Sync, and then pair again. |
| `tapToPayDisabled` | A pairing request reached a terminal that has Tap to Pay turned off, so the terminal can't take sales. | Show a message that tells the merchant to contact support. |

<a id="a-pairing-response-contains-an-error"></a>
### A pairing response contains an error

If the response to a pairing request contains an `error`, your app doesn't store a reader identifier. Show the merchant a message for the error. For example, the code in [Step 3 of Connect your app to Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync#step-3-pair-your-app-with-mobile-sync-on-an-iphone) calls the `errorMessage(for:)` function.

<a id="a-sale-response-contains-an-error"></a>
### A sale response contains an error

For a sale or a signature capture, only `notProvisioned` and `standaloneMode` mean that Mobile Sync didn't run the request. There's no result to get from our gateway, so show the merchant a message.

For any other `error`, get the result from our gateway as you normally do.

The following code creates a message for each error and handles the two errors that mean the sale didn't run. If the error is `notProvisioned`, the code also unpairs the old reader identifier and asks the merchant to pair again.

```swift
import AppSwitchContract

/// A message for the merchant for an `error` code in a response from Mobile Sync.
func errorMessage(for code: String?) -> String {
    switch code {
    case AppSwitchURL.unsupportedSchemeError:
        "This app opened Mobile Sync in the wrong way."
    case AppSwitchURL.notProvisionedError:
        "Mobile Sync was reset. Pair again to continue."
    case AppSwitchURL.standaloneModeError:
        "Mobile Sync is in Standalone mode. Switch it back to Payroc Cloud in its App settings."
    case AppSwitchURL.modeSwitchInProgressError:
        "Mobile Sync is switching modes. Finish the switch there, and then pair again."
    case AppSwitchURL.tapToPayDisabledError:
        "Tap to Pay is turned off for this terminal. Contact support."
    case .some(let other):
        "Mobile Sync couldn't run the request (\(other))."
    case .none:
        "Mobile Sync didn't return a result."
    }
}

/// Call for a sale response that contains notProvisioned or standaloneMode. See Run a sale, Step 4.
func handleSaleError(_ code: String) {
    saleGeneration += 1                        // the sale is no longer current; see Cancel a sale
    pendingSale?.cancel()                      // the sale never ran
    isWaitingForSaleReturn = false
    showMessage(errorMessage(for: code))

    if code == AppSwitchURL.notProvisionedError {
        unpair()                               // the reader identifier is out of date
        askToPairAgain()                       // pair with Mobile Sync again
    }
    // For standaloneMode, keep the pairing.
}
```

<a id="the-sale-is-voided-or-doesnt-complete"></a>
## The sale is voided or doesn't complete

When a sale ends, Mobile Sync returns to your app with a `status` that tells you what Mobile Sync encountered. The `status` is only an indication of the outcome. Use it to decide what to show the merchant while you retrieve the instruction from our gateway.

| **Status** | **What happened** | **Was the customer charged?** |
| --- | --- | --- |
| `completed` | Mobile Sync got a response to the sale. | Yes, if our gateway approved the sale. |
| `cancelled` | The merchant or our gateway canceled the sale. | No |
| `failed` | A terminal error occurred before authorization, or your request failed. | No |
| `voided` | A network failure occurred during authorization or surcharge reversal. Mobile Sync saves the pending reversal and sends it again when it's online. | Maybe, until the reversal is processed. |
| `timeout` | The sale was idle for too long, or no request arrived. | No |
| `unavailable` | Mobile Sync couldn't connect to our gateway. | No |
| `readerUnavailable` | The card reader in Mobile Sync couldn't start. | No |

The instruction contains more information about the issue and the true status of the sale. Use the following table to decide what to show the merchant after you get the instruction from our gateway. If the sale is still in progress, you can offer an option to check the status again.

| **Our gateway says** | **Status** | **What to show** | **Offer Check status?** |
| --- | --- | --- | --- |
| The sale is completed | Any, including `voided` | The receipt, as in [Step 5 of Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale#step-5-get-the-result-and-show-the-receipt). For `voided`, also read [Mobile Sync voids the sale](#mobile-sync-voids-the-sale). | No |
| The sale is still in progress | `voided` | The payment is voided and a reversal is pending. | Yes |
| The sale is still in progress | Any other status | The sale is still processing. | Yes |
| The sale ended but isn't completed | `voided` | Mobile Sync voided the payment. Include the status from our gateway. | No |
| The sale ended but isn't completed | Any other status | The status and text from our gateway. | No |

The following code handles the cases where the sale isn't completed. If our gateway is still processing the sale, the code keeps `isWaitingForSaleReturn` as `true`, so that your app can check again.

**Important:** Don't write the full response from our gateway to a log. It can contain card data.

```swift
import AppSwitchContract
import AppSwitchGatewayReference

/// Call when our gateway doesn't report the sale as completed.
func handleIncompleteSale(_ outcome: InstructionOutcome, hint: AppSwitchURL.ReturnStatus?) {
    if outcome.stillInProgress {
        showMessage(hint == .voided
            ? "The payment is voided and a reversal is pending."
            : "The sale is still processing.")
        showCheckStatusButton()                // the button calls checkStatus()
        return
    }

    isWaitingForSaleReturn = false
    if hint == .voided {
        showMessage("Mobile Sync voided the payment. Status: \(outcome.status)")
    } else {
        // Don't show outcome.body for a completed sale. It's the full payment, which can contain card data.
        showMessage(outcome.succeeded
            ? "The sale completed, but your app couldn't read the payment details. Check the status again."
            : outcome.body)                    // for example, "cancelled: <the error from our gateway>"
    }
}
```

<a id="mobile-sync-voids-the-sale"></a>
### Mobile Sync voids the sale

A `voided` status from Mobile Sync means that Mobile Sync can't confirm whether our gateway received the result. Mobile Sync saves the pending reversal and sends it when Mobile Sync is back online.

If you retrieve the instruction and our gateway reports the sale as completed, your app can show the receipt. However, our gateway might have approved the sale while a reversal is still in progress.

**Important:** Before the merchant hands over goods for a sale that returned `voided`, retrieve the sale and check if our gateway reversed it.

To retrieve the sale, send a `GET` request to `/payments` with the `orderId` that you stored in [Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale). If our gateway reversed the sale, it returns a response that contains a `status` of `reversal`.

```swift
import AppSwitchGatewayReference

/// True when our gateway shows that the sale was reversed.
func isReversed(orderId: String, terminalId: String, using client: PayrocGatewayClient) async -> Bool {
    let payments = (try? await client.listPayments(orderId: orderId, processingTerminalId: terminalId)) ?? []
    return payments.first?.isReversed ?? false
}
```

<a id="you-cant-confirm-the-result"></a>
## You can't confirm the result

Sometimes your app can't get the result from our gateway. Don't tell the merchant that the sale succeeded or failed. Keep the instruction ID, tell the merchant that you can't confirm the result, and offer a **Check status** button.

You can't confirm the result in the following scenarios:

- [The response never arrives](#the-response-never-arrives).
- [Your app can't reach our gateway](#your-app-cant-reach-our-gateway).
- [Our gateway returns a `404`](#our-gateway-returns-a-404).

<a id="the-response-never-arrives"></a>
### The response never arrives

If the merchant switches back to your app or closes Mobile Sync during a sale, Mobile Sync cancels the sale and your app gets no response. When your app becomes active, wait 1.5 seconds for a response, and then check with our gateway up to three times, three seconds apart.

Mobile Sync can send a late `cancelled` response the next time the merchant opens it, for up to five minutes. For more information about how to handle this scenario, go to [The merchant leaves Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale#the-merchant-leaves-mobile-sync).

<a id="your-app-cant-reach-our-gateway"></a>
### Your app can't reach our gateway

If the iPhone's network connection is down after a sale, the first check can fail. Our gateway reports the sale as in progress until Mobile Sync reconnects and sends its result.

<a id="our-gateway-returns-a-404"></a>
### Our gateway returns a `404`

Our gateway doesn't recognize the reader identifier that your app stored. You need to program your app to pair with Mobile Sync again to get a new reader identifier. For more information, go to [The reader identifier is out of date](#the-reader-identifier-is-out-of-date).

The following code handles an error when your app tries to get the result. [Step 5 of Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale#step-5-get-the-result-and-show-the-receipt) calls it.

```swift
/// Call when your app can't get the result from our gateway.
func handleUnconfirmedSale(_ error: Error) {
    if isUnknownDevice(error) {
        isWaitingForSaleReturn = false
        askToPairAgain()                       // pair with Mobile Sync again
        return
    }

    // Keep the instruction ID, and check again when your app becomes active. See Cancel a sale.
    isWaitingForSaleReturn = true
    showMessage("We couldn't confirm the result. Check your internet connection, and then check the status again.")
    showCheckStatusButton()
}
```

<a id="check-the-status-again"></a>
### Check the status again

When the merchant selects **Check status**, call the following `checkStatus()` function. It checks the instruction with our gateway once, and works for a sale and for a signature capture. It uses the `activeClient`, `activeInstructionId`, `activeInstructionType`, and `handledInstructionIds` variables from [Step 3 of Run a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/run-a-sale#step-3-switch-to-mobile-sync-and-send-the-request), which stay set after Mobile Sync returns.

If your app doesn't capture signatures, remove the `.signature` branch.

```swift
import AppSwitchGatewayReference

/// Call when the merchant selects Check status. Works for a sale and for a signature capture.
func checkStatus() {
    guard let client = activeClient, let instructionId = activeInstructionId else { return }
    let type = activeInstructionType
    Task {
        do {
            let outcome = try await client.completeInstruction(type: type,
                                                               instructionId: instructionId,
                                                               maxAttempts: 1)
            if outcome.stillInProgress {
                showCheckStatusButton()               // still processing, so the merchant can check again
                return
            }
            isWaitingForSaleReturn = false
            handledInstructionIds.insert(instructionId)
            if type == .signature {
                pendingSignature = nil                // the signature capture is finished
                if outcome.succeeded {
                    showSignature(ReceiptParser.rows(fromJSON: outcome.body))   // see Capture a signature
                } else {
                    showMessage(outcome.status)
                }
            } else {
                showResult(outcome, hint: nil)        // from Run a sale, Step 5
            }
        } catch {
            handleUnconfirmedSale(error)
        }
    }
}
```

<a id="next-step"></a>
## Next step

After you handle errors, you can [submit your app to the App Store](/guides/payments/tap-to-pay-on-iphone/mobile-sync/submit-to-the-app-store).
