> 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).

# Tratando falhas

{% 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](/caf-sdk/caf-sdk-pt-br/ios/getting-started-with-the-sdk-5.md).

{% endhint %}

Quando uma verificação de vivacidade falha, o SDK retorna um `LivenessFailure` objeto. Esse objeto contém um `causa` parâmetro, que é um identificador de string que informa exatamente por que o processo não foi bem-sucedido.

Entender e lidar com o `causa` parâmetro é fundamental para fornecer 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`). |

***

### Ao usar o `causa` Parâmetro

O `causa` parâmetro, retorna uma string literal constante bruta (por exemplo, `"TOO_DARK"` ou `"FACE_TOO_FAR"`).

Melhor prática: não exiba essas strings brutas diretamente aos seus usuários finais. Em vez disso, interceptar o `causa` string e mapeá-la para uma mensagem localizada e amigável ao usuário na interface do seu app para orientá-los sobre como corrigir o problema.

#### Causas de falha disponíveis

Ao usar o [iProov](https://github.com/iProov/ios) provedor, se a captura da imagem for bem-sucedida, mas o mecanismo falhar ao autenticar ou processar o rosto, o SDK retorna um `FaceRecognitionFailure`.

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

#### Estável `causa` valores

| `causa`                                                      | 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 desfocado               |
| `motion_issue`                                               | Movimento                     |
| `background_issue`                                           | Plano de fundo / contraste    |
| `device_issue`, `device_restart`                             | Dispositivo                   |
| `system_error`                                               | Sistema                       |
| `rejeitado`, `timeout`, `user_not_found`, `processing_fault` | Transação / servidor          |

***

### Exemplo de implementação

Aqui está um exemplo de como você pode tratar um `LivenessFailure` e mapear o `causa` parâmetro para orientações úteis ao usuário:

```swift
func mapFailureToUX(_ failure: LivenessFailure) -> (code: String, message: String) {
    switch failure {
    case .imageCaptureFailure(let text):
        return ("image_capture", text)
    case .faceRecognitionFailure(_, let cause):
        let code = cause.lowercased()
        let message = localizedHint(forCause: code) ?? "Falha na verificação. Tente novamente."
        return (code, 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
    }
}
```


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
