要約
- 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"}}