> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/ios/getting-started-with-the-sdk-1/handling-failures.md). Agents can also search and read this documentation through its [MCP server](https://docs.caf.io/~gitbook/mcp).

# Tratamento de Falhas

Referência para eventos de delegate do Certta Liveness, erros bloqueantes e mapeamento de falhas no iOS, incluindo tratamento de sucesso, diagnósticos e orientações de UI.

{% hint style="warning" %}

## Este guia abrange a versão 7.0.0 e superiores. Para versões anteriores à 7.0.0, consulte a [documentação legada](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/ios/getting-started-with-the-sdk-5.md).

{% endhint %}

Quando uma verificação de liveness falha, o SDK retorna um `LivenessFailure` objeto. Para falhas de reconhecimento facial, ele contém duas strings:

* **`cause`**: um código estável em snake\_case que informa exatamente por que o processo não teve sucesso (por exemplo `face_too_far`).
* **`description`**: uma mensagem localizada e legível para humanos que descreve a mesma falha.

Entender e lidar com o `cause` parâmetro é fundamental para fornecer um feedback claro e acionável aos seus usuários, para que eles possam corrigir o problema e tentar novamente.

***

### Callbacks do delegado (`CerttaLivenessDelegate`)

| Delegado      | Significado                                                                                  |
| ------------- | -------------------------------------------------------------------------------------------- |
| `didFail(_:)` | Falha de negócio: o fluxo foi concluído, mas o resultado não foi aceito (`LivenessFailure`). |

***

### Usando o `cause` Parâmetro

O `cause` parâmetro retorna um código estável em snake\_case (por exemplo, `"too_dark"` ou `"face_too_far"`). Se o motivo não puder ser classificado, `cause` é `"unknown"`.

Melhor prática: não exiba esses códigos brutos diretamente aos usuários finais. Em vez disso, mapeie o `cause` código para uma mensagem localizada e amigável na interface do seu app para orientá-los sobre como corrigir o problema. Use `description` como mensagem de fallback ou para diagnósticos, mas não baseie sua lógica nele: o texto é localizado e pode mudar.

{% hint style="info" %}
`description` está disponível em **7.8.0**. Antes da 7.8.0, `faceRecognitionFailure` tinha apenas `result` e `cause`, e `cause` guardava a mensagem localizada. Atualize seu `switch` para o padrão de três valores mostrado no [exemplo abaixo](#example-implementation).
{% endhint %}

#### Causas de Falha Disponíveis

Se a captura da imagem for bem-sucedida, mas o rosto não puder ser autenticado ou processado, o SDK retorna uma `faceRecognitionFailure`.

Abaixo está a lista de possíveis `cause` valores retornados especificamente durante esta fase:

#### Estável `cause` valores

| `cause`                                                     | Dica                          |
| ----------------------------------------------------------- | ----------------------------- |
| `unknown`                                                   | Não classificado              |
| `too_much_movement`                                         | Movimento excessivo da cabeça |
| `too_bright`, `too_dark`, `lighting_issues`                 | Iluminação                    |
| `misaligned_face`                                           | Não alinhado com o guia       |
| `eyes_closed`                                               | Olhos fechados                |
| `face_too_far`, `face_too_close`                            | Distância                     |
| `sunglasses`, `eyewear`                                     | Óculos                        |
| `obscured_face`                                             | Rosto coberto                 |
| `multiple_faces`                                            | Mais de um rosto              |
| `face_not_found`                                            | Nenhum rosto na região        |
| `frames_blurry`                                             | Muito borrado                 |
| `motion_issue`                                              | Movimento                     |
| `background_issue`                                          | Plano de fundo / contraste    |
| `device_issue`, `device_restart`                            | Dispositivo                   |
| `system_error`                                              | Sistema                       |
| `rejected`, `timeout`, `user_not_found`, `processing_fault` | Transação / servidor          |

***

### Exemplo de Implementação

Aqui está um exemplo de como você pode lidar com uma `LivenessFailure`, mapear o `cause` código para orientações úteis ao usuário e recorrer a `description`:

```swift
func mapFailureToUX(_ failure: LivenessFailure) -> (code: String, message: String) {
    switch failure {
    case .imageCaptureFailure(let text):
        return ("image_capture", text)
    case .faceRecognitionFailure(_, let cause, let description):
        let message = localizedHint(forCause: cause) ?? description
        return (cause, message)
    }
}

private func localizedHint(forCause cause: String) -> String? {
    switch cause {
    case "too_dark", "too_bright", "lighting_issues":
        return "Melhore a iluminação e tente novamente."
    case "multiple_faces":
        return "Apenas uma pessoa deve estar na câmera."
    case "timeout":
        return "O tempo acabou. Tente novamente."
    default:
        return nil
    }
}
```

***

### Bridges híbridas (Flutter / React Native)

Quando o fluxo Face Liveness é executado pelos bridges do Flutter ou do React Native, uma falha de reconhecimento facial é entregue como um evento de falha com estas chaves de payload:

| Chave         | Valor                                                                                   |
| ------------- | --------------------------------------------------------------------------------------- |
| `type`        | Sempre `FaceRecognitionFailure` para esta classe de falha.                              |
| `cause`       | O código estável em snake\_case (veja [estável `cause` valores](#stable-cause-values)). |
| `description` | A mensagem legível para humanos e localizada. Disponível a partir da 7.8.0.             |
| `response`    | O payload assinado, quando disponível.                                                  |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.caf.io/caf-sdk/caf-sdk-pt-br/ios/getting-started-with-the-sdk-1/handling-failures.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
