|
| 1 | +package com.example.demo.login.controller; |
| 2 | + |
| 3 | +import org.springframework.dao.DataAccessException; |
| 4 | +import org.springframework.http.HttpStatus; |
| 5 | +import org.springframework.stereotype.Component; |
| 6 | +import org.springframework.ui.Model; |
| 7 | +import org.springframework.web.bind.annotation.ControllerAdvice; |
| 8 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 9 | + |
| 10 | + |
| 11 | +@ControllerAdvice |
| 12 | +@Component |
| 13 | +public class GlobalControllerAdvice { |
| 14 | + |
| 15 | + @ExceptionHandler(DataAccessException.class) |
| 16 | + public String dataAccessExceptionHandler(DataAccessException e, Model model) { |
| 17 | + // 例外クラスのメッセージをModelに登録 |
| 18 | + model.addAttribute("error", "内部サーバーエラー(DB):GlobalControllAdvice"); |
| 19 | + model.addAttribute("message", "DataAccessExceptionが発生しました。"); |
| 20 | + // HTTPのエラーコード(500)をModelに登録 |
| 21 | + model.addAttribute("status", HttpStatus.INTERNAL_SERVER_ERROR); |
| 22 | + |
| 23 | + return "error"; |
| 24 | + } |
| 25 | + |
| 26 | + @ExceptionHandler(Exception.class) |
| 27 | + public String exceptionHandler(Exception e, Model model) { |
| 28 | + // 例外クラスのメッセージをModelに登録 |
| 29 | + model.addAttribute("error", "内部サーバーエラー:GlobalControllAdvice"); |
| 30 | + model.addAttribute("meaage", "Exceptionが発生しました。"); |
| 31 | + |
| 32 | + // HTTPエラーコード(500)をModelに登録 |
| 33 | + model.addAttribute("status", HttpStatus.INTERNAL_SERVER_ERROR); |
| 34 | + |
| 35 | + return "error"; |
| 36 | + } |
| 37 | +} |
0 commit comments