0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RestControllerAdviceを使って全体共通のExceptionHandlerを設定しよう!!

Posted at

@ 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 すればハンドリングされてエラーレスポンスが返されます!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?