Plumber框架自定义JSON解析错误处理Swagger测试异常排查
自定义Plumber错误处理:无效JSON在Swagger中返回500而非预期400状态码
我使用Plumber构建自定义错误处理逻辑,其中missing_val_check函数可检查数据框中的缺失列,若存在缺失则返回400状态码及自定义消息,该函数在Swagger和curl中均可正常工作。
我希望对无效JSON实现类似的自定义处理,让safely_parse_json返回400状态码和自定义消息,但该函数表现不符合预期:通过Swagger传递无效JSON时,会返回500状态码和默认错误;而通过curl传递时,则可正常返回自定义错误。
代码示例
plumber.R 代码
library(plumber) library(tidyverse) api_error <- function(message, status, res) { res$status = status error <- structure( list(message = message, status = status), class = c("api_error", "error", "condition") ) signalCondition(error) } missing_val_check <- function(x, res) { cols_with_na <- names(x)[apply(is.na(x), 2, any)] if(length(cols_with_na) > 0 ){ msg = paste("NA values found in columns:", paste(cols_with_na, collapse = ", ")) api_error(message = msg, status = 400, res=res) } } safely_parse_json <- function(req, res){ parse <- purrr::safely(.f = jsonlite::fromJSON, otherwise = NULL) result <- parse(req$postBody, simplifyVector = FALSE) if(length(result[["error"]]) > 0){ api_error(message = paste("JSON Error:", result[["error"]][["message"]]), status = 400, res = res) } else { return(result[["result"]]) } } #* @param req:object #* @serializer json #* @post /test function(req, res) { parsed <- dplyr::bind_rows( safely_parse_json(req, res) ) df <- parsed |> mutate(across(where(is.numeric), \(x) ifelse(x ==0, NA, x))) # force a NA for demo purposes missing_val_check(df, res) paste(parsed) }
启动Plumber的代码
pr("plumber.R") %>% pr_run(port=8000)
测试场景
示例1:无错误场景
输入:{"a":4, "b":3}或curl --data '{"a":4, "b":3}' http://localhost:8000/test
表现:运行正常,符合预期。示例2:缺失值错误场景
输入:{"a":4, "b":0}或curl --data '{"a":4, "b":0}' http://localhost:8000/test
表现:返回400状态码和自定义错误消息,Swagger和curl均正常,符合预期。示例3:无效JSON错误场景
输入:{"a":4, "b:0}或curl --data '{"a":4, "b:0}' http://localhost:8000/test
表现:curl返回自定义400错误;Swagger返回500状态码和默认错误,不符合预期。
内容的提问来源于stack exchange,提问作者acircleda
相关产品推荐
相关产品推荐

