From 399eac351b1bc29d5047dbac96486c281be1b05c Mon Sep 17 00:00:00 2001 From: Murilo Ijanc Date: Mon, 27 Jul 2026 20:38:27 -0300 Subject: Report the municipality a missing CEP would have belonged to A CEP that fails a lookup is rarely a random number: it is usually someone who knows the city and guessed, and the classic guess is the -000 that 957 municipalities never received. The API now answers those 404s with a faixa naming the municipality that owns the band the number fell into, which is the difference between telling a user "invalid CEP" and "no such CEP in Areal/RJ". It is context for an error and never an address, so it rides on the cepis_not_found condition instead of turning the failure into a success, and cep_ini/cep_fim are the endpoints that exist rather than the range the Correios publish - the interval between them is sparse, which is what ceps counts. Parsing is deliberately unable to signal: a faixa that is null, an array, a string or half a body leaves a clean not-found behind, because the caller asked for the CEP, not for the decoration on its absence. --- R/http.R | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'R/http.R') diff --git a/R/http.R b/R/http.R index 6ef4511..08e8ddc 100644 --- a/R/http.R +++ b/R/http.R @@ -173,12 +173,22 @@ json_object <- function(body) { data } -api_message <- function(body, fallback) { +# The counterpart of json_object() for a body that is already an error: it +# never signals, because a broken error body must not replace the error the +# caller is being told about. Missing, malformed, empty: all of them NULL. +json_field <- function(body, name) { data <- tryCatch( jsonlite::parse_json(decode_body(body), simplifyVector = FALSE), error = function(e) NULL ) - message <- if (is.list(data)) data[["mensagem"]] else NULL + if (!is.list(data) || is.null(names(data))) { + return(NULL) + } + data[[name]] +} + +api_message <- function(body, fallback) { + message <- json_field(body, "mensagem") if (is.character(message) && length(message) == 1L && nzchar(message)) { message } else { -- cgit v1.3