Spring Bootでエラーハンドリングをする方法はいくつかあります。
この中の2つをご紹介。
1.@ControllerAdviceでの実装
ExceptionControllerAdvice.java
@ControllerAdvice
public class ExceptionControllerAdvice {
@InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("controller advice: init binder");
}
@ExceptionHandler(Exception.class)
public String exception(Exception e) {
System.out.println("controller advice: exception Handler");
System.out.println(e.getMessage());
return "error";
}
@ModelAttribute
public void modelAttribute(){
System.out.println("controller advice:model Attribute");
}
}
2.コントローラー内に直接記述
XXController.java
@RequestMapping("/xx")
public class XXController {
@ExceptionHandler(Exception.class)
public String handling(Exception e) {
return "/err";
}
}