Appearance
独自例外クラスおよびハンドラを作成
自作の例外クラスを作成し、ハンドラによってエラーメッセージをAPIレスポンスとして返却します。
実装
exception/SampleException.kt
kotlin
package nob.example.easyapp.exception
/**
* サンプルの自作例外クラスです。
* ExceptionクラスのString?型をオーバーライドしてString型としています。
*/
class SampleException(override val message: String) : Exception()handler/SampleExceptionHandler.kt
kotlin
package nob.example.easyapp.handler
import nob.example.easyapp.exception.SampleException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
/**
* SampleExceptionのハンドラです。
*/
@RestControllerAdvice
class SampleExceptionHandler {
@ExceptionHandler(SampleException::class)
fun handleSampleException(e: SampleException): ResponseEntity<SampleExceptionResponse> {
return ResponseEntity(SampleExceptionResponse(e.message), HttpStatus.UNPROCESSABLE_CONTENT)
}
/**
* SampleException発生時のレスポンスボディです。
*/
data class SampleExceptionResponse(
/**
* エラーメッセージ
*/
val message: String
)
}下記要領で例外を投げると例外発生時のレスポンスボディが返ります。
kotlin
override fun login(inModel: LoginInModel): LoginOutModel {
if (inModel.name == "") {
throw SampleException("ユーザ名を入力してください")
}
val users = usersRepository.findByName(inModel.name) ?: return LoginOutModel(false)
return LoginOutModel(users.password == inModel.password)
}