LoginSignup
0
0

More than 1 year has passed since last update.

KotlinでRestControllerAdvice

Posted at

要約

  • Kotlinのクラス参照はKClass型で、::classを使うと取得できる(Javaでいうと.class
  • @ExceptionHandlerの引数にKClass型を与えると、この例外を拾って適切なレスポンスを返してくれる

実装

この例は、HogeNotFoundExceptionが発生したときに404 (Not Found)を返すようなコントローラの実装です。

import com......HogeNotFoundException // 自由に
import com......dto.ErrorResponse // 自由に
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(HogeNotFoundException::class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    fun handleHogeNotFoundException(exception: HogeNotFoundException): ErrorResponse {
        return ErrorResponse(exception.message)
    }
}

ErrorResponseは以下のように実装しています。

import com.fasterxml.jackson.annotation.JsonRootName

@JsonRootName("error")
class ErrorResponse (val message: String)

なんらかのHTTPリクエストに対して内部でHogeNotFoundExceptionが発生すると、次のようなレスポンスが返ります。

{"error":{"message":"error message"}}

参考

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