我有一個獲取名稱和描述引數的 API 端點(兩者都是必需的)
createSomething(@RequestParam(value = "name") String name,@RequestParam(value = "description") String description)
如果客戶沒有提供任何這些,他將收到 400 Bad Request
有沒有辦法告訴客戶缺少哪個欄位?為“錯誤請求”回應提供更多資訊
uj5u.com熱心網友回復:
您可以將驗證與自定義訊息一起使用:
@GetMapping("/name-for-month")
public String getNameOfMonthByNumber(@RequestParam @Min(1) @Max(value = 12, message = “month number has to be less than or equal to 12”) Integer month) {
// ...
}
uj5u.com熱心網友回復:
有多種處理 Rest 錯誤的方法,請在下面找到針對您的問題的至少 5 個解決方案的鏈接:
- 例外處理程式
- HandlerExceptionResolver (ResponseStatusExceptionResolver 這是最適合您的案例,如果您使用 spring 5 ,這是第 4 個)
- 控制器建議
- 回應狀態例外
- 處理 Spring Security 中的訪問被拒絕
https://www.baeldung.com/exception-handling-for-rest-with-spring
uj5u.com熱心網友回復:
由于這兩個引數都是強制性的,如果您嘗試發送不帶引數的請求,您將收到 400(錯誤請求)。
一種解決方法可能是使請求引數不是強制性的(以便可以在沒有引數的情況下發送請求)并提供默認值以防不提供引數
createSomething(@RequestParam(value = "name", required=false, defaultValue = null) String name,@RequestParam(value = "description", required=false, defaultValue = null) String description)
在函式中,您可以檢查 null,如下所示 -
if (name == null) // name parameter is not provided
if (description == null) // description paramter is not provided
并且,如果請求中未提供任何一個/多個引數,您還可以根據條件發送錯誤回應。
uj5u.com熱心網友回復:
我看到了多個答案,但沒有一個足夠具體。
1)
默認情況下,Spring 能夠在錯誤訊息中報告請求中缺少哪些引數或其他違規行為。
但是,從 Spring Boot 2.3 版開始,特定的錯誤訊息被隱藏了,因此無法向用戶透露任何敏感資訊。
您可以使用版本server.error.include-message: always之前的默認機制屬性,2.3并允許 spring 再次為您撰寫錯誤訊息。
2)
如果您負擔不起,因為其他敏感資訊可能會從其他例外中泄露,那么您必須為此特定情況提供自己的例外處理程式
以下內容可以放在同一個控制器中,也可以放在另一個標有@ControllerAdvice
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity handleMissingParams(MissingServletRequestParameterException ex) {
return ResponseEntity.badRequest().body(String.format("Missing parameter with name:%s", ex.getParameterName()));
}
uj5u.com熱心網友回復:
可能您還需要啟用應用程式屬性
server.error.include-message=always
更多屬性供參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/445251.html
上一篇:while回圈增加了額外的時間
