Guides
API principles

Errors

Each BB layer answers errors in its own format. Learn which body to expect from the gateway, from OAuth and from each API.

BB answers from several layers, and each one has its own error format: the gateway (app key and route), OAuth, token validation and each API's backend. Mimicr reproduces the bodies byte for byte, including the spacing and the odd Content-Type of some. Handle the error by HTTP status first, then by the format of the API you called.

Order of the checks

The gateway checks, in this order:

  1. The API exists (prefix /pix/v2, /cobrancas/v2, /pagamentos-lote/v1, /extratos/v1 or /extratos/v2).
  2. The method and path exist in that API (a trailing slash counts as an unknown path).
  3. gw-dev-app-key was sent and is valid.
  4. Authorization: Bearer is a valid, unexpired token of the same application.
  5. The token has the operation's scope.
  6. The API's backend validates the request.

Gateway: app key and route

Pix and Cobranças, without gw-dev-app-key (403):

json
{ "detail": "A chave de aplicacao (AppKey) nao foi informada", "userHelp": "A chave de aplicacao deve ser informada como parametro de consulta (query parameter gw-dev-app-key)", "errorCode": "403", "bbMsg": { "categoria": "SISTEMA", "tipo": "ERRO" } }

With an unknown app key, the same format with "detail": "A chave de aplicacao (AppKey) informada e invalida".

SituationStatusBody
Unknown API prefix404{"errors":[{"codigo":404,"versao":1,"mensagem":"Not Found","ocorrencia":"N/A"}]} (served as text/html)
Unknown route, with app key404{"statusCode":404,"error":"Not Found","message":"Api not found"}
Unknown route, without app key400{ "statusCode": 400, "error": "Bad Request", "message": "A key must be provided by request queryString parameter \"gw-dev-app-key\"" }

Pagamentos em Lote answers in plain text (text/plain;charset=us-ascii), always 403: Authentication parameters missing without app key, and Authentication failed with an invalid app key, an invalid token or a missing scope.

Extratos v1 answers 400 with A key must be provided by request header "X-Application-Key" or "X-Developer-Application-Key" or queryString parameters "gw-app-key" or "gw-dev-app-key" without app key, and 403 Application key is not allowed to call this resource method with an invalid app key. Extratos v2 uses the detail/userHelp body above.

OAuth

POST /oauth/token answers in the RFC 6749 format:

json
{ "error": "invalid_client", "error_description": "Identificador ou credencial inválidos" }
errorStatusWhen
invalid_request400No Authorization: Basic (Software cliente não identificado.)
invalid_client401Wrong client_id or client_secret
unsupported_grant_type400grant_type other than client_credentials
invalid_scope400scope missing, comma-separated or with an unknown scope
too_many_requests429More than 10 tokens in 10 minutes, only with the homologação limit on

Another method on the endpoint answers 405. See Authentication.

Token and scope

Missing, invalid or expired token (Pix, Cobranças and Extratos), 401:

json
{"statusCode":401,"error":"Unauthorized","message":"Bad credentials","attributes":{"error":"Bad Credentials"}}

Token without the operation's scope:

APIStatusBody
Pix403AcessoNegado problem (below)
Cobranças, Extratos403{"statusCode":403,"error":"Forbidden","message":"Application key is not allowed to call this resource method"}
Pagamentos em Lote403Authentication failed (text)

API Pix

The Pix backend uses BACEN's problem format in BB's namespace:

json
{
  "type": "https://api.bb.com.br/api/v2/error/CobOperacaoInvalida",
  "title": "Cobrança inválida.",
  "status": 400,
  "detail": "A requisição que busca alterar ou criar uma cobrança para pagamento imediato não respeita o _schema_ ou está semanticamente errada.",
  "correlationId": "API-BB-d7e20dd5-fb3f-4fb5-bda6-f3e01af79d02",
  "violacoes": [
    { "razao": "O campo cob.valor.original não respeita o _schema_.", "propriedade": "cob.valor.original" }
  ]
}
type (suffix)StatusWhen
CobOperacaoInvalida, CobVOperacaoInvalida, LoteCobVOperacaoInvalida400Invalid charge or batch
PayloadLocationOperacaoInvalida400Invalid location
PixDevolucaoInvalida400Invalid refund
WebhookOperacaoInvalida400Invalid webhook
ConsultaInvalida400List parameters (inicio, fim, window longer than 5 days)
NaoEncontrado404Unknown resource, or empty list
AcessoNegado403Token without the scope
ServicoIndisponivel503Internal failure

Broken business rules come in detail, sometimes without violacoes. Note: in Pix, a list with no results answers 404, not an empty list.

API Cobranças

Each endpoint has its own envelope:

FormatEndpointsExample
Erro-v4POST /boletos, gerar-pix, cancelar-pix, GET /boletos/{id}/pix, baixa operacional, convênios, retorno de movimento{"erros":[{"codigo":"4874915","versao":"1","mensagem":"Nosso Número já incluído anteriormente.","providencia":"Informar outro Nosso Número.","ocorrencia":"meO5nvkRVesPc5HWJsTqIsR0"}]}
Erro-v2GET /boletos{"erros":[{"codigoMensagem":"4722678","versaoMensagem":"1","textoMensagem":"Não existem boletos a serem listados.","textoProvidencia":"","codigoRetorno":"1053"}]}
ErroGET, PATCH /boletos/{id}, POST /boletos/{id}/baixar{"errors":[{"code":"4010673.1","message":"Boleto não localizado.","action":""}]}

Malformed JSON answers 400 {"erros":[{"codigo":"999","ocorrencia":"N/A","mensagem":"JSON de Requisição Inválido (null)","versao":"1"}]}. An internal failure answers 500 with Erro-v4 3996135.

Pagamentos em Lote

Business errors use erros, with a hexadecimal ocorrencia:

json
{"erros":[{"codigo":"4","versao":"1","mensagem":"Número da requisição 346625 já utilizado para este contrato. Consulte GET /proximos-numeros-requisicao.","ocorrencia":"beccafb7ff596468465b84e4ec690f08"}]}

The newer endpoints (/requisicoes/{idRequisicao}, /proximos-numeros-requisicao and the Pix receipt) use {"code":"404","message":"Requisição 346625 não encontrada.","variaveisMonitoradas":[]}.

An accepted batch may hold invalid payments: the request answers 201 with estadoRequisicao 2 (partial) or 3 (inconsistent), and each payment carries its error codes in erros. These codes follow BB's reason table (for example 18 invalid CPF check digit, 53 payment date before today). See Release and queries.

Extratos

VersionEnvelopeExample
v1erros{"erros":[{"codigo":"5738678","versao":"1","mensagem":"O período entre a data inicial e a data final é superior a 31 dias.","ocorrencia":"ICCE01792731467710"}]}
v2Modelo Resposta{"code":"5738445","message":"A data final informada é superior a data atual. Refaça a requisição ajustando a data.","variaveisMonitoradas":[]}

The date codes are listed in Extratos. An account that does not belong to the application answers 403 6646500; an account with no entries in the period answers 404 with an empty code and the message Not Found.

When to retry

StatusRetry?How
400, 403, 404, 422NoFix the request
401Yes, onceGet a new token and retry
429YesWait; on OAuth, reuse the token until it expires
500, 503YesExponential backoff; for a batch POST, check the request first

Test it

The control API's chaos injects, per API, latency and 500 errors ({"statusCode":500,"error":"Internal Server Error","message":"Erro na execução da solicitação."}), 503 (ServicoIndisponivel problem) or 429 ({"statusCode":429,"error":"Too Many Requests","message":"Rate limit exceeded"}), before or after processing the call. See Sandbox control.