![](/img/trans.png)
[英]How to return custom error message in Spring Boot for /error page
[英]Spring Boot how to return custom error message when validating @PathVariable parameters
是否可以向路徑變量添加一些自定義驗證消息?
我有一些 GET
@GetMapping("/v2/tw/{id}")
public TwDto getTw(Authentication auth, @PathVariable Long id) {
在/v2/tw/someString
的情況下,我想捕獲錯誤並添加一些自定義錯誤消息,例如“無效的 tw ID”... 怎么做? 在ControllerAdvice
添加一些ExceptionHandler
?
對於您的特定用例,您可以在 Controller 或@ControllerAdvice
class 中使用@ExceptionHandler
,如此處所示。 例如,我為此返回 NOT_FOUND 錯誤。
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "this is the reason")
public void handle() {
}
在您啟用之前,您可能看不到實際錯誤響應中的reason
server:
error:
include-message: always
如果您認為您的@ExceptionHandler
僅在 Controller class 中需要,您可以將該方法保留在 controller 中。 或者,您可以創建一個@ControllerAdvice
class 並將該方法放在那里,以便您可以在應用程序中的多個控制器之間重用。
但是,如果您想要更復雜的驗證,我建議將id
類型保留為 String,然后手動轉換為 Long 並執行驗證。 這樣做您可以拋出自己的 RuntimeException 並處理不同的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.