Skip to content

Instantly share code, notes, and snippets.

@kodaitakahashi
Last active July 29, 2017 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodaitakahashi/c78ade5331ff18ffe959ff38c3e3fa01 to your computer and use it in GitHub Desktop.
Save kodaitakahashi/c78ade5331ff18ffe959ff38c3e3fa01 to your computer and use it in GitHub Desktop.
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