我有一個正在實施的控制器ErrorController
它處理我的spring專案中發生的任何錯誤,下面是代碼。
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public void springWebErrors() {
return "springWebErrorPage"
}
}
另外,我已經提到
server.error.path=/error
但我被困在有時資料可能不符合需要的地方,所以我想提供我的定制訊息,
關于如何實作它有什么想法嗎?(謝謝)
uj5u.com熱心網友回復:
據我了解你的擔心,
您希望您的應用程式在用戶發送無效資料時處理錯誤/例外,我使用自定義例外、ControllerAdvice 和例外處理程式在我的代碼中應用了相同的東西,
請檢查以下代碼,這可能有用。
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = PageNotFoundException.class)
public String pageNotFoundException(PageNotFoundException exception){
return "error/404";
}
@ExceptionHandler(value = AuthFailedException.class)
public String authFailedException(AuthFailedException exception){
return "error/401";
}
@ExceptionHandler(value = ServerException.class)
public String serverException(ServerException exception){
return "error/500";
}
}
說明:@ControllerAdvice & @ExceptionHandler是全域錯誤控制器,您可以訪問檔案here
@Controller
public class CustomizedErrorController implements ErrorController {
@RequestMapping("/error")
public void handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
if(statusCode == HttpStatus.NOT_FOUND.value()) {
throw new PageNotFoundException();
}
else if(statusCode == HttpStatus.UNAUTHORIZED.value()) {
throw new AuthFailedException();
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
throw new ServerException();
}
}
else{
throw new OtherException();
}
}
}
您還可以從您的實作或控制器檔案中拋出您的自定義例外。
我希望,它有幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515167.html
標籤:春天弹簧靴弹簧MVC例外
