Skip to content

独自例外クラスおよびハンドラを作成

自作の例外クラスを作成し、ハンドラによってエラーメッセージを API レスポンスとして返却します。

  • 例外クラス
package nob.example.easyapp.exception;

/**
 * サンプルの自作例外クラスです。
 *
 */
public class SampleException extends Exception {

    public SampleException(String message) {
        super(message);
    }
}
  • 例外ハンドラ
package nob.example.easyapp.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.Value;
import nob.example.easyapp.exception.SampleException;

/**
 * サンプル例外のハンドラです。
 *
 */
@RestControllerAdvice
public class SampleExceptionHandler {

    /**
     * サンプル例外が投げられた際のハンドリングを行います。
     *
     * @param e
     * @return 例外メッセージ
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ExceptionHandler(SampleException.class) // SampleExceptionが投げられた際に動く
    public ResponseEntity<SampleExceptionResponseBody> handleSampleException(SampleException e) {

        return new ResponseEntity(new SampleExceptionResponseBody(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY);
    }

    /**
     * サンプル例外発生時のレスポンスボディです。
     */
    @Value
    public class SampleExceptionResponseBody {

        /** エラーメッセージ */
        private String message;
    }
}

上記で例外クラスおよびハンドラを実装し、下記のように例外を投げると例外発生時のレスポンスボディが返ります。

    @Override
    public LoginOutModel login(LoginInModel inModel) throws SampleException {

        if (inModel.getName() == null) {
            throw new SampleException("ユーザ名がnullです。");
        }

        return new LoginOutModel(
                usersRepository.findByName(inModel.getName()).getPassword().equals(inModel.getPassword()));
    }