@ RestControllerAdvice とは
@ControllerAdvice
と @ResponseBody
が組み合わされた アノテーションです
ControllerAdvice は アプリ全体のコントローラに適用される共通の処理 を定義できる
ExceptionHandler の 動かし方
ExceptionHandler は 同クラス内で発生したExceptionをハンドリングし、設定したオブジェクトを返します.
そのため ExceptionHandlerを動かしたい場合は 同じクラスに記述 するか RestControllerAdvice で 全体のクラス共通のExceptionとすることで動く!!
実装例
実際に以下のような例でハンドリングをした場合の処理です
- ユーザーを検索したが見つからない場合の処理
- フロントエンドサーバ からの入力を受け付け、内容が不正だった場合の処理
例外のハンドリング
package test.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ExceptionController {
// 入力不正の自作例外
@ExceptionHandler(InvalidRequestException.class)
public ProblemDetail InvalidRequestExceptionHandler(InvalidRequestException e) {
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
problemDetail.setDetail("InvalidRequest");
return problemDetail;
}
// ユーザー不明の自作例外
@ExceptionHandler(UserNotFoundException.class)
public ProblemDetail UserNotFoundExceptionHandler(UserNotFoundException e) {
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.FORBIDDEN, e.getMessage());
problemDetail.setDetail("NotFoundUser");
return problemDetail;
}
}
入力不正の例外
package test.web.exception;
public class InvalidRequestException extends RuntimeException {
public InvalidRequestException(String message) {
super(message);
}
}
ユーザー不明の例外
package myenglish.web.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
あとは該当のRestControllerで throw new すればハンドリングされてエラーレスポンスが返されます!