Last active
July 29, 2017 16:31
-
-
Save kodaitakahashi/c78ade5331ff18ffe959ff38c3e3fa01 to your computer and use it in GitHub Desktop.
Kotlinで例外クラスの作り方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
*/ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Person( | |
val name: String, | |
val age: Int | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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