gpt4 book ai didi

java - 在 Spring Boot 中处理无效的 PathVariables

转载 作者:行者123 更新时间:2023-12-01 18:11:53 25 4
gpt4 key购买 nike

假设我有一个 GET Controller /api/product/{id} ,其中 id 是一个整数。处理非整数 id 请求的最佳方法是什么?目前 Spring 只是抛出 java.lang.NumberFormatException 并返回 400。

最佳答案

您可以进行路径变量验证,假设 id 应该是正 int 值。

@GetMapping("/api/product/{id}")
public void getProduct(@PathVariable("id") @Min(value = 0) Integer id) {
// ...
}

阅读上面请求验证的更多内容 here .

如果您知道产品 ID 具有一定范围的 int 值,您甚至可以尝试 @Range

关于java - 在 Spring Boot 中处理无效的 PathVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com