「SpringBoot」アノテーション@ExceptionHandlerで例外(exception)処理のサンプル
環境
Windows10 64bit
Spring Boot 2.6.2
Spring Tool Suite 4
JDK 11
書式
1.例外クラス名の定義
public class 例外クラス名 extends RuntimeException{
例外クラス名(String message) {
//継承元クラスのコンストラクタ
super(message);
}
}
2.アノテーション@ExceptionHandlerの利用
@ExceptionHandler(例外クラス名.class)
public String testExceptionHandle(例外クラス名 e, Model model) {
model.addAttribute("属性名",e);
return "ファイルパス;
}
使用例
1.コントローラのメソッドで独自の例外処理を行う(ChaController.java)
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/cft2")
public class ChaController {
public static final String TT = "sos";
@GetMapping()
public String funA(Model model) {
funB();
return "cft2/index";
}
//関数funBの定義
void funB() {
String str = "sos";
if (str.equals(TT)) {
throw new SampleException("定義例外throw message テスト");
}
}
@ExceptionHandler(SampleException.class)
public String exceptionHadnle(SampleException e, Model model) {
model.addAttribute("result", e);
return "cft2/index";
}
}
2.独自の例外クラスの定義(SampleException.java)
package com.example.demo;
//RuntimeExceptionクラスを継承 独自の例外クラスの定義
public class SampleException extends RuntimeException {
private static final long serialVersionUID = 1L;
SampleException(String message) {
//継承元クラスのコンストラクタ
super(message);
}
}
3.ビューのファイル
(src/main/resources/templates/cft2/index.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>例外エラーメッセージ処理表示ページ</title>
</head>
<body >
<p th:text="${result}"></p>
</body>
</html>
4.プロジェクトを右クリックして、「実行(R)」->「Spring Boot アノテーション」をクリックします
5.動作確認
http://127.0.0.1:8080/cft2
画面に「com.example.demo.SampleException: 定義例外throw message テスト」が表示されます