我GET在控制器中有一個方法可以獲取很多引數。我想在出現例外或無效輸入的情況下重定向 URL,并回傳(列印到客戶端)帶有附加訊息的例外。
我的函式如下所示:
@GetMapping("/v1.0/hello/{userName}")
public ClientResponse getDetails(@PathVariable(value = "userName") String userName,
@RequestParam(value = "expInp1", required = false) int expInp1,
@RequestParam(value = "expInp2", required = false) int expInp2,
@RequestParam(value = "expInp3", required = false) int expInp3){
// do something...
return clientResponse;
}
ClientResponse 是一個包含所有相關詳細資訊且無法更改的物件。
例如,如果有人插入以下 URL /v1.0/hello/{userName}?expInp4=XXX,我想/v1.0/hello/使用合適的訊息將他們重定向到。
是否有沒有大量代碼的 Spring 注釋?如果沒有,在我的情況下最好的方法是什么?
uj5u.com熱心網友回復:
創建一個帶有@RestControllerAdvice或@ControllerAdvice注解的新類,以在 Spring Boot 中全域處理例外。
參考這個鏈接
uj5u.com熱心網友回復:
你可以看看@RestControllerAdvice加上@ExceptionHandler注解。您可以按照以下步驟創建重定向系統:
創建你自己的例外
public class RedirectException extends RuntimeException{ private String redirectUrl; public RedirectException(String message, String rUrl) { super(message); this.redirectUrl = rUrl; } }創建您的控制器建議
@RestControllerAdvice public class ErrorController { @ExceptionHandler(RedirectExecption.class) public void handleRedirect(RedirectException re, HttpServletResponse res) { res.sendRedirect(re.getRedirectUrl); } }當您想在運行的代碼中發送重定向回應時,只需使用您想要訪問的重定向網址拋出一個 redirectException
ps 您可以使用相同的機制來構建錯誤處理系統。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322709.html
