Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Kotlinで例外クラスの作り方
class BadRequestExcetpion(val httpStatusCode: String, msg: String? = null): RuntimeException(msg)
// インスタンス生成時にRuntimeExceptionにmsgを渡しています
// Javaで書き直した場合
/*
class BadRequestException extends RuntimeException{
String httpStatusCode;
BadRequestException(String httpStatusCode, String msg){
super(msg)
this.httpStatusCode = httpStatusCode
}
}
*/
data class Person(
val name: String,
val age: Int
)
@RestController
@RequestMapping(value= "/persons")
class PersonController{
@RequestMapping(value = "/persons/{id}" method = arrayOf(RequestMethod.GET))
fun getPerson(@PathVariable(value = "id") id: String): Person =
when (id){
"one" -> Person(id, 10),
"two" -> Person(id, 20),
else -> throw NotFoundException(403, "Not found Person!!")
}
@ExceptionHandler(NotFoundException::class)
@ResponseStatus(HttpStatus.NOT_FOUND)
fun notFound(e: NotFoundException) : Map<String, String?> =
mapOf(Pair("status", e.status), Pair("message", e.message))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment